Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
Hint:
- How many majority elements could it possibly have?
⌊ n/3 ⌋
times)存在,那麼一定不會超過兩個,證明用反證法很容易理解。接下來就是如何找出這可能的兩個元素。可以分兩步,找兩個candidate和驗證candidate出現的次數是否超過⌊ n/3 ⌋
times。 找兩個候選candidate的方法就是Moore投票法,和Majority Element中類似。需要驗證的原因是,不同於Majority Element中已經限制了主元素一定存在,這題不一定存在這樣的元素,即使存在個數也不確定,所以需要驗證過程。時間複雜度O(n),空間複雜度O(1).public class Solution {
public List<Integer> majorityElement(int[] nums) {
//moore voting
//0632
int candidate1 = 0, candidate2 = 0, times1 = 0, times2 = 0;
int n = nums.length;
for(int i = 0; i < n; i++){
if(nums[i] == candidate1) {
times1++;
} else if(nums[i] == candidate2){
times2++;
} else if(times1 == 0) {
candidate1 = nums[i];
times1 = 1;
} else if(times2 == 0){
candidate2 = nums[i];
times2 = 1;
} else{
times1--;times2--;
}
}
times1 = 0; times2 = 0;
for(int i = 0; i < n; i++){
if(nums[i] == candidate1) times1++;
else if(nums[i] == candidate2) times2++;
}
List<Integer> res = new ArrayList<Integer>();
if(times1 > n/3) {
res.add(candidate1);
}
if(times2 > n/3) {
res.add(candidate2);
}
return res;
//0649
}
}