您的位置:首页 > 其它

169. Majority Element

2016-03-19 00:08 316 查看
1.Question

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.

2.Code

codeA

class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate = 0, count = 0;
for(int i = 0; i < nums.size(); i++)
{
if(count == 0)
{
count = 1;
candidate = nums[i];
}
else if(candidate == nums[i])
count++;
else
count--;
}
return candidate;
}
};


codeB

class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map <int, int> map;
int n = nums.size();
if(n == 1)
return nums[0];
for(int i  = 0; i < n; i++)
{
if(map.find(nums[i]) != map.end())
{
if(++map[nums[i]] > n/2)
return nums[i];
}
else
{
map[nums[i]] = 1;
}
}
}
};


codeC

class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = nums.size();
if(n == 1)
return nums[0];
sort(nums.begin(), nums.end());
for(int i = 0; i < n; i++)
{
if(nums[i] == nums[i + n/2])
return nums[i];
}
}
};


3.Note

a.写了三个版本的解法,leetcode上跑的时间分为别16ms,
36ms ,40ms.

codeA的空间复杂度为1,时间复杂度为n。所用思想为:占n/2以上的元素能够抵消剩下小于n/2的元素的数目,则candidate能保留着majorityElement.

codeB就是哈希表的思想,统计元素的个数,然后大于n/2时就输出对应的元素。

codeC需要先排序,思想是占n/2的元素在全集中的长度大于n/2,则能保证nums[i]=nums[i+n/2],再遍历一遍就可以找出来。但是排序消耗时间。

可以得出,codeA是最优的解法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: