码迷,mamicode.com
首页 > 其他好文 > 详细

169. 求众数

时间:2018-10-10 01:03:13      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:来源   pre   nts   并且   details   href   res   targe   family   

给定一个大小为 的数组,找到其中的众数。众数是指在数组中出现次数大于 ? 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 
版权声明:本文为博主原创文章,转载请附上博文链接!

 

169. 求众数

标签:来源   pre   nts   并且   details   href   res   targe   family   

原文地址:https://www.cnblogs.com/jj81/p/9763843.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!