您的位置:首页 > 其它

169. Majority Element

2016-11-08 23:29 344 查看
题目:

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.

思路:
1. 由题目可知,输入不为空,且有且只有一个majority元素。
2. 我的思路是用一个map,标记每个值的出现次数,当遇到一个majority元素时,终止。(讨论区有其他更优化的算法)

代码:

int majorityElement(vector<int>& nums) {
map<int, int> res;
int size = nums.size();
cout<<size<<endl;
if (size == 1) return nums[0];
for(int num : nums){
if (res.find(num) == res.end()) res[num] = 1;
else{
res[num] += 1;
if (res[num] > size / 2) return num;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Majority Element