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.

哈希

通过map计数即可

class Solution {
public:
    int majorityElement(vector<int>& nums) 
    {
        map<int, int> cnt;
        for(int i=0; i < nums.size(); i++)
            cnt[ nums[i] ]++;

        int n = nums.size();
        for(map<int, int>::iterator iter = cnt.begin(); iter != cnt.end(); iter++)
            if( iter->second > n/2 )
                return iter->first;
    }
};

优化

每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的

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

你可能感兴趣的:(169. Majority Element)