169

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

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

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

猜你喜欢

转载自www.cnblogs.com/qian-lu/p/9339707.html
169
今日推荐