题目:
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.
解答:
这道题需要点技巧。既然已知数组中某元素E出现次数大于⌊ n/2 ⌋
次,设想把这个数组分组,所有元素E分成一组,为G1,其余所有元素分成一组,为G2,显然G1包含的元素个数比G2多,且G1里元素与G2里元素都不相同!注意,这是重点。既然这样,那么,我每次删除一对不相同的元素,最后剩下的元素肯定是E!!(这句话看不懂的要多看几遍)
代码如下(通过OJ):
public class Solution {
public int majorityElement(int[] num) {
int candidate = 0,nTimes = 0;
for(int i=0;i<num.length;i++){
if(nTimes == 0){
candidate = num[i];
nTimes = 1;
} else {
if(candidate == num[i])
nTimes++;
else
nTimes--;
}
}
return candidate;
}
}
这道题还可以推广一下,从n/2推广到n/k,即数组中必然有个MajorityElement的出现次数大于 ⌊ n/k ⌋,如何找出这个元素呢??同样道理,分为k组,每次找到k个不相同的元素,删除之,最后剩下元素中出现次数最多的就是MajorityElement。
贴出n/3的情况代码,供大家参考:
public class Solution006 {
/*
* Given an array of size n, find the majority element.
* The majority element is the element that appears more than (n/3) times.
* You may assume that the array is non-empty and the majority element always exist in the array.
*/
public int majorityElement(int[] num) {
int candidate1 = 0,c1Times = 0;
int candidate2 = 0,c2Times = 0;
for(int i=0;i<num.length;i++){
if(c1Times == 0){
candidate1 = num[i];
c1Times = 1;
} else if (c2Times == 0) {
if(candidate1 == num[i])
c1Times++;
else {
candidate2 = num[i];
c2Times = 1;
}
} else {
if (candidate1 == num[i])
c1Times++;
else if(candidate2 == num[i])
c2Times++;
else {
c1Times--;
c2Times--;
}
}
}
return c1Times > c2Times ? candidate1:candidate2;
}
}