您的位置:首页 > 其它

多数投票算法

2015-10-15 22:20 399 查看
今天在leetcode看到一个题目:Majority Element,题目内容是:


Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.


主要简单的想法是将数组排序,因为多数的元素超过一半,因此排序后中间的元素必定是要求的多数元素。代码如下:

public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}

时间复杂度为O(nlogn)。那能否只需O(n)时间复杂度内完成任务呢?答案是可以的,一种思路是利用hashmap。另一种是就是 Boyer–Moore majority vote algorithm 。算法思路是:


每次都找出一对不同的元素,从数组中删掉,直到数组为空或只有一种元素。 不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。


相应的Majority Element 的 Solution 为:

//Boyer–Moore majority vote algorithm
public class Solution {
public int majorityElement(int[] nums) {
int result = 0;
int count = 0;
for(int i = 0; i < nums.length; ++i) {
if(count == 0) {
result = nums[i];
count++;
} else if(result == nums[i]) {
count++;
} else {
count--;
}
}
return result;
}
}

我的Github: leetcode解答https://github.com/wanggang3333

leetcode-majorityelement :majorityelement

参考:

1.【leetcode 哈希表】Majority Element ——csdn

2.Moore's voting algorithm——csdn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: