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) {
int n = nums.size();
map<int, int> m;
for (int i = 0; i != n; ++i)
{
m[nums[i]]++;
}
for (auto i : m)
{
if (n % 2 == 1)
{
if (i.second >= n/2 +1)
return i.first;
}
else
{
if (i.second >= n/2)
return i.first;
}
}
return 0;
}
};