题目描述:
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.
解法一:
使用一个hash表来存储数组中每个元素出现的次数,如果出现次数大于 ⌊ n/2 ⌋ 的元素,直接返回这个元素。
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> hash_map;
for(int i = 0; i < nums.size(); i++){
if(hash_map.find(nums[i]) != hash_map.end()){
hash_map[nums[i]]++;
}else{
hash_map[nums[i]] = 1;
}
if( hash_map[nums[i]] > nums.size() / 2 )
return nums[i];
}
return 0;
}
};