letecode [169] - Majority Element

 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%的用户

猜你喜欢

转载自www.cnblogs.com/lpomeloz/p/11004189.html