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.
题意:找数组里数目超过一半的那个元素。
思路:排序,然后中间那个元素
public int majorityElement(int[] num) {
Arrays.sort(num);
return num[num.length/2];
}
看了solution,好多种方法 = =
又做了里面那种叫做Moore voting algorithm的,可以达到O(n)
We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
- If the counter is 0, we set the current candidate to x and the counter to 1.
- If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
public int majorityElement(int[] num) {
int candidate = num[0];
int counter = 1;
for (int i=1; i<num.length; i++) {
if (counter == 0) {
candidate = num[i];
counter++;
} else {
if (num[i] == candidate) {
counter++;
} else {
counter--;
}
}
}
return candidate;
}
网上搜了一下,有大神说 “ 每找出两个不同的element,则成对删除。最终剩下的一定就是所求的。”
这么一说马上豁然开朗。
solution还介绍了个分治方式的,谷歌搜了下,看到一份解题报告,只有伪码,感觉伪码好像是不对的,还是跟着实现,果然没过 = =
坐等大神代码
procedure GetMajorityElement(a[1...n])
Input: Array a of objects
Output: Majority element of a
if n = 1: return a[1]
k = n/2
elemlsub = GetMajorityElement(a[1...k])
elemrsub = GetMajorityElement(a[k+1...n]
if elemlsub = elemrsub:
return elemlsub
lcount = GetFrequency(a[1...n],elemlsub)
rcount = GetFrequency(a[1...n],elemrsub)
if lcount > k+1:
return elemlsub
else if rcount > k+1:
return elemrsub
else return NO-MAJORITY-ELEMENT