一.题目描述
给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。
进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。
https://leetcode-cn.com/problems/majority-element-ii/
二.代码
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
int cand1 = nums[0], count1 = 0;
int cand2 = nums[0], count2 = 0;
for (int num : nums) {
if (cand1 == num) {
count1++;
continue;
}
if (cand2 == num) {
count2++;
continue;
}
if (count1 == 0) {
cand1 = num;
count1++;
continue;
}
if (count2 == 0) {
cand2 = num;
count2++;
continue;
}
count1--;
count2--;
}
count1 = 0;
count2 = 0;
for (int num : nums) {
if (cand1 == num) count1++;
else if (cand2 == num) count2++;
}
if (count1 > nums.length / 3) res.add(cand1);
if (count2 > nums.length / 3) res.add(cand2);
return res;
}