您的位置:首页 > 其它

Majority Element

2015-11-05 21:32 281 查看
题目:

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) {
size_t m = nums.size() / 2;
map<int,int> nums_count;
vector<int>::iterator it = nums.begin();
while(it != nums.end())
nums_count[*it++]++;
map<int,int>::iterator it2 = nums_count.begin();
while(it2 != nums_count.end())
{
if( it2->second > m)
return it2->first;
it2++;
}
}
};


另一种思路,好像比我的慢

int majorityElement1(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size()/2];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: