题目:
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) {
map<int, int>imap;
int mid;
if (nums.size() % 2 == 0)
mid = nums.size() / 2;
else mid = nums.size() / 2 + 1;
for (int i = 0; i < nums.size(); i++)
{
++imap[nums[i]];
if (imap[nums[i]] >= mid)
return nums[i];
}
return false;
}
};