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.
给定一个长度为n的数组,找出出现次数大于⌊ n/2 ⌋ 的元素。
思路:
使用unordered_map<int,int> m来统计每个元素出现的次数,其中只有一个元素的出现次数会大于n/2,所以以元素出现次数大于n/2作为查找条件。
Code:
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int> m;
int n = nums.size();
for(int i=0; i<n; i++){
if(++m[nums[i]]>n/2) return nums[i];
}
}
};