题意如标题所说。注意,默认此数组中有元素的出现次数为len/2。
刚开始看到这道题,觉得简单到爆。直接sort一遍再取len/2处的元素不就行了嘛。这样的时间复杂度为nlogn。
后来看了下面这种别人的做法,觉得十分巧妙。膜膜膜!
这种算法叫majority vote algorithm,时间复杂度为n。
大致思路是:
As we sweep we maintain a pair consisting of a current candidate and a counter. Initially, the current candidate is unknown and the counter is 0.
When we move the pointer forward over an element e:
If the counter is 0, we set the current candidate to e and we set the counter to 1.
If the counter is not 0, we increment or decrement the counter according to whether e is the current candidate.
粘的代码,如下:
public class Solution {
public int majorityElement(int[] num) {
int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;
}
return major;
}
}