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;
}
本文介绍两种有效的方法来找出数组中的多数元素,即出现次数超过数组长度一半的元素。第一种方法使用Boyer-Moore投票算法,通过遍历数组进行计数;第二种方法先对数组排序,然后遍历数组找到符合条件的多数元素。
1406

被折叠的 条评论
为什么被折叠?



