【LeetCode】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实现,统计某元素出现次数,一旦超过n/2,则返回此元素值。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int len = nums.size();
        if(len==0) return 0;
        if(len==1) return nums[0];
        map<int,int> int_map;
        int i;
        for(int i=0; i < len; i++)
        {
            ++int_map[nums[i]];
            if(int_map[nums[i]] > len/2)
             return nums[i];
        }
    }
};


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