Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Note: The algorithm should run in linear time and in O(1) space.
Example 1:
Input: [3,2,3]
Output: [3]
Example 2:
Input: [1,1,1,3,3,2,2,2]
Output: [1,2]
数组size=n,找出次数>n/3的所有元素
要求线性运行时间和O(1)空间
思路:
因为是线性时间,所以不能brute force, O(1) space也不能用hashtable
所以用投票法,一个元素的时候参照投票法
这里因为出现次数>n/3, 数组整体长度为n,所以最多有2个主元素,把之前的一个主元素改为两个主元素
分两步,先找candidate, 再验证candidate是否是主元素
public List<Integer> majorityElement(int[] nums) {
int count1 = 0;
int count2 = 0;
int a = 0;
int b = 0;
List<Integer> result = new ArrayList<>();
int n = nums.length;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == a) {
count1 ++;
}else if(nums[i] == b) {
count2 ++;
}else if (count1 == 0) {
a = nums[i];
count1 = 1;
}else if (count2 == 0) {
b = nums[i];
count2 = 1;
}else{
count1 --;
count2 --;
}
}
count1 = 0;
count2 = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == a) {
count1 ++;
}
//防止出现重复元素,所以用else
else if(nums[i] == b) {
count2 ++;
}
}
if(count1 > n/3) {
result.add(a);
}
if(count2 > n/3) {
result.add(b);
}
return result;
}