您的位置:首页 > 其它

[leetcode] 169. Majority Element

2016-03-26 17:26 393 查看
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.

这道题是找数组中个数超过一半的元素,题目难度为Easy。

最容易想到的办法是排序或用Hash Table统计元素个数,排序取中点元素的方法时间复杂度O(nlogn),Hash Table则需要额外的存储空间,这里介绍一下Majority Vote Algorithm,多数投票算法,时间复杂度O(n),空间复杂度O(1)。算法思路其实很简单,先上代码为敬。具体代码:class Solution {
public:
int majorityElement(vector<int>& nums) {
int major, count = 0;

for(int num:nums) {
if(count) {
if(major == num) ++count;
else --count;
}
else {
major = num;
++count;
}
if(count > nums.size()/2) break;
}

return major;
}
};遍历数组,如果计数器为0,将当前元素暂定为Majority
Element并将计数器置为1;如果计数器不为0,当前元素等于Majority Element时计数器加1,不等的话减1,这样如果存在超过一半的元素,最终记录下的Majority
Element就是它。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode