您的位置:首页 > 其它

leetcode解题报告(21):Majority Element

2017-05-16 18:14 405 查看

描述


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.


分析

unordered_map来做,以元素值为key,元素个数为value。然后遍历这个map,判断有没有元素个数大于 ⌊ n/2 ⌋,如果有,就返回这个元素,否则继续遍历,直到遍历结束。

代码如下:

class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int>m;
for(int num : nums)
++m[num];
for(auto it = m.begin(); it != m.end(); ++it){
if(it->second > nums.size() / 2)return it->first;
}
return 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: