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.
思路:
。。。
解:
class Solution {
public:
int majorityElement(vector<int>& nums) {
std::map<int, int> numsOfNums;
for(size_t idx = 0; idx < nums.size(); idx++)
{
numsOfNums[nums[idx]]++;
if(numsOfNums[nums[idx]] > (nums.size()/2))
return nums[idx];
}
return 0;
}
};