您的位置:首页 > 其它

leetcode Majority Element

2015-11-16 16:12 387 查看
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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

这道题我还是用map做的,对于某个关键字有这种计数类的性质的题目用map真的很好用,关键点还是记得map里面的元素是pair,我们需要(*i).first,最后是32ms,还不错吧
一次提交就accepted还是非常开心的。

class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int,int> eleTimes;
int temp=0,count=0,sta=0;
sta=nums.size()/2;
if(sta==0) return nums[0];
for(auto i=nums.begin();i!=nums.end();i++){
temp=(*i);
++eleTimes[temp];
}
for(auto j=eleTimes.begin();j!=eleTimes.end();j++){
count=(*j).second;
if(count>sta) return (*j).first;
}
}

};


后来还看了一种比较简单的思想,但是理解起来比较困难

[C++ Solution] [O(n) computation/O(1) space] The problem can be extended to ⌊n/k⌋ situation

Find k different element, and "remove" them as a group, the remaining element must be the element that appears more than ⌊n/k⌋ times. (Detailed explanation is given in comment)

In this problem, k equals to 2.

Thus we "remove" each pair of 2 different elements, and the remaining element that do not have its counterpart is the desired element.

就是成k对去“删除”不相同的元素:

例如5个元素的时候,5,3,4,3,3这种情况下,5,3会被删除,4,3会被删除,最后就剩下3;

5,3,3,4,3:5,3会被删除,3,4会被删除,留下3

5,3,3,3,4:5,3会被删除,candidate是第二个3,因为接下来的元素还是3,于是Ntimes变成了2,即使后面的4与其不相同,Ntimes没有被减至0,于是,被返回。

class Solution {
public:
int majorityElement(vector<int> &num) {
int nTimes = 0;
int candidate = 0;
for(int i = 0; i < num.size(); i ++)
{
if(nTimes == 0)
{
candidate = num[i];
nTimes = 1;
}
else
{
if(candidate == num[i])
nTimes ++;
else
nTimes --;
}
}
return candidate;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: