您的位置:首页 > 其它

leetcode 169- Majority Element

2017-12-13 21:53 423 查看
Given an array of size n, find themajority element. The majority element is the element that appears more than ⌊n/2 ⌋times.
You may assume that the array isnon-empty and the majority element always exist in the array.

题目的意思是有一个数组,数组中有一个数出现的次数大于数组长度的一半,让找出这个数。

方法1:就是对数组进行排序,排序之后的数组的中位数就是目标值。
但是注意冒泡、选择等排序方法都超时了,复杂度O(n2)太高了,所以用sort快排。时间复杂度O(nlogn).
AC代码:

class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size()/2];
}
};

方法2:把每个数出现的次数用一个HashMap记录下来,key是数组中的数,value是该数出现的次数。因为最后想找出现次数最大的数,也就是找最大value对应的key值。时间复杂度O(n).
AC代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int>temp;
for(int x:nums)
{
if (++temp[x]>nums.size()/2)
return x;
}
}
};


方法3:可以采用类似于下棋对子的方法。从头开始遍历数组,只要有不一样的两个数就相互对掉,那么最后剩下的那个数就是所求解。这种方法相比于前两种方法很巧妙,最不容易想到。但是时间复杂度O(n),相比于方法一的sort快排O(nlogn)降低了时间复杂度。不利用额外空间,相比于方法二的HashMap降低了空间复杂度。
AC代码:

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