zoukankan      html  css  js  c++  java
  • 169. 求众数

    给定一个大小为 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

    你可以假设数组是非空的,并且给定的数组总是存在众数。

    示例 1:

    输入: [3,2,3]
    输出: 3

    示例 2:

    输入: [2,2,1,1,1,2,2]
    输出: 2

    【关键点】 出现次数大于 ⌊ n/2 ⌋

    解法一:
    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int res=0,counts=0;
            for(int x:nums){
                if(counts==0){
                    res=x;
                    counts=1;
                }else if(res==x) ++counts;
                else --counts;
            }
            return res;
        }
    };
    
    ---------------------
    作者:L_Aster 
    来源:CSDN 
    原文:https://blog.csdn.net/gl486546/article/details/79783937?utm_source=copy 
    版权声明:本文为博主原创文章,转载请附上博文链接!

    解法二:

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            return nums[nums.size()/2];
        }
    };
    
    
    ---------------------
    作者:江江蒋 
    来源:CSDN 
    原文:https://blog.csdn.net/qq_33168253/article/details/79946041?utm_source=copy 
    版权声明:本文为博主原创文章,转载请附上博文链接!
  • 相关阅读:
    CSS同时选择器
    create-react-app之proxy
    mysql limit语句
    给tbody加垂直滚动条的具体思路
    MySql数据类型范围
    block、inline、inline-block
    javascript sourcemap
    session of express
    React中innerHTML的坑
    box-sizing
  • 原文地址:https://www.cnblogs.com/jj81/p/9763843.html
Copyright © 2011-2022 走看看