[每日LeetCode] 169. Majority Element

  |   0 评论   |   653 浏览

Description:

Given an array of size_n_, find the majority element. The majority element is the element that appearsmore 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

思路:题目要求数组中的众数。先将数组中的数字存入map结构,key为元素值,value为出现的次数,判断value次数大于n/2则输出key值。


C++代码

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int,int> map;
        for(int num : nums)
            map[num]++;
        for(auto it = map.begin(); it !=map.end(); ++it){
            if (it->second > nums.size()/2)
                return it->first;
        }
        return 0;
    }
};

运行时间:20ms

运行内存:11.1M

评论

发表评论