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 cnt = 0;
int ans = 0;
for(int i = 0; i < nums.size(); ++i)
{
if(cnt == 0)
{
ans = nums[i];
cnt++;
}
else
{
if(nums[i] == ans)
cnt++;
else
cnt--;
}
}
return ans;
}
};
class Solution {
public:
int majorityElement(vector<int>& nums) {
int i , len, max=0, count=1;
len = nums.size();
max = len/2;
max=max+1;
if(len==1)
return nums[0];
sort(nums.begin(),nums.end());
for(i=0;i<len;i++)
{ if(nums[i]==nums[i+1])
count++;
else
{
if(count>=max)
return nums[i];
count=1;
}
}
return 0;
}
};
int majorityElement(vector<int>& nums) {
map<int,int> m;
int ret = -1;
for(int i = 0;i<nums.size();i++)
{
m[nums[i]]++;
}
for(map<int,int>::iterator it = m.begin();it != m.end();it++)
{
if((*it).second*2 >= nums.size())
{
ret = (*it).first;
break;
}
}
return ret;
}