题目描述:
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 ⌋次的元素。
思路:哈希一下,再遍历哈希表即可。
c++代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int, int> hash;
for (auto i : nums)
{
hash[i]++;
}
int length = nums.size() % 2 == 0 ? nums.size() / 2 : (nums.size() + 1) / 2;
for (auto i : hash)
{
if (i.second >= length)
{
return i.first;
}
}
}
};