标签:leetcode majority element map
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.
其实就是找到序列中出现次数最多的元素,而且已经提出假设这个序列不为空,同时这样的数字是一定存在的
我自己的解法比较土,就是利用一个map记录了每一个元素的出现的次数
class Solution {
public:
int majorityElement(vector<int> &num) {
int length = num.size();
map<int,int> NumCount;
for(int i = 0; i < length; i++)
{
NumCount[num[i]]++;
}
int maxNum = 0;
int RetVal = 0;
map<int,int>::iterator mapit = NumCount.begin();
for(;mapit != NumCount.end(); mapit++)
{
if(mapit->second > maxNum)
{
maxNum = mapit->second;
RetVal = mapit->first;
}
}
return RetVal;
}
};
每找出两个不同的element,则成对删除。最终剩下的一定就是所求的。
可扩展到? n/k ?的情况,每k个不同的element进行成对删除。但是这个是在这样的数据一定存在的前提下才可以,如果有两个数出现的次数相同,这个就不好扩展了
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;
}
};
class Solution {
public:
int majorityElement(vector<int> &num) {
int n = num.size();
sort(num.begin(),num.end());
return num[n/2];
}
};标签:leetcode majority element map
原文地址:http://blog.csdn.net/xietingcandice/article/details/43271135