问题:
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.
解决:
① 将数组排序后计算出现次数。
class Solution { //5ms
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
Arrays.sort(nums);
int count = 1;
int len = nums.length;
for (int i = 1;i < nums.length;i ++){
if (nums[i] == nums[i - 1]){
count ++;
}else {
if (count > len / 3){
res.add(nums[i - 1]);
}
count = 1;
}
}
if (count > len / 3){
res.add(nums[len - 1]);
}
return res;
}
}
② 推举法,规律:任意一个数组出现次数大于n/3的众数最多有两个。
class Solution { //3ms
public List<Integer> majorityElement(int[] nums) {
int num1 = 0;
int num2 = 0;
int count1 = 0;
int count2 = 0;
for (int num : nums){
if (num == num1){
count1 ++;
}else if (num == num2){
count2 ++;
}else if (count1 == 0){
num1 = num;
count1 ++;
}else if (count2 == 0){
num2 = num;
count2 ++;
}else {
count1 --;
count2 --;
}
}
count1 = 0;
count2 = 0;
for (int num : nums){
if (num == num1){
count1 ++;
}else if (num == num2){
count2 ++;
}
}
List<Integer> res = new ArrayList<>();
if (count1 > nums.length / 3) res.add(num1);
if (count2 > nums.length / 3) res.add(num2);
return res;
}
}