首页 > 其他 > 详细

letecode [169] - Majority Element

时间:2019-06-11 16:39:43      阅读:104      评论:0      收藏:0      [点我收藏+]

 Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

题目大意

   求数组中的众数。

理  解:

   看的大神解法。

  标记数量最多的元素val,遇到相同的数count++,遇到不同的数count--,当count等于0时,更新val为新的元素。

代 码 C++:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int val = nums[0];
        int count=1;
        int i;
        for(i=1;i<nums.size();++i){
            if(count==0)
                val = nums[i];
            if(nums[i]==val)
                count++;
            else
                count--;
        }
        return val;
    }
};

运行结果:

   执行用时 :28 ms, 在所有C++提交中击败了81.41%的用户

   内存消耗 :11 MB, 在所有C++提交中击败了87.66%的用户

letecode [169] - Majority Element

原文:https://www.cnblogs.com/lpomeloz/p/11004189.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!