229. Majority Element II
Medium
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]
题意
给定一个长度为n的数组,求出现次数大于n/3的元素(一个或两个)
思路
LeetCode 169. Majority Element的姊妹题,也是摩尔投票法的变式,实现O(n)时间复杂度和O(1)空间复杂度的算法。
使用两套变量(cand1, cnt1),(cand2, cnt2)分别存储第一个可能的元素和第二个可能的元素及其出现次数。cand1, cand2(如果存在的话),出现的次数会大于其余元素出现次数之和,因此摩尔投票法仍然适用。
和寻找出现次数大于n/2的元素不同的一点是,在本题中,符合要求的元素有可能有一个([1,1,1,1,2] -> 1),有可能有两个([1,1,2,2,3] -> 1,2),通过一次循环求出cand1和cand2之后,还要通过一次循环求出cand1和cand2的出现次数验证是否大于n/3.
代码
class Solution {
public List<Integer> majorityElement(int[] nums) {
int cand1 = 0, cand2 = 0, cnt1 = 0, cnt2 = 0;
for (int num: nums) {
if (cnt1 == 0 && num != cand2) {
cand1 = num;
}
if (cnt2 == 0 && num != cand1) {
cand2 = num;
}
if (cand1 == num) {
++cnt1;
} else if (cand2 == num) {
++cnt2;
} else {
if (cnt1 > 0) {
--cnt1;
}
if (cnt2 > 0) {
--cnt2;
}
}
}
// System.out.println(cand1 + " " + cand2);
cnt1 = 0;
cnt2 = 0;
for (int num: nums) {
if (cand1 == num) {
++cnt1;
} else if (cand2 == num) {
++cnt2;
}
}
ArrayList<Integer> arr = new ArrayList<Integer>();
if (cnt1 > nums.length/3) {
arr.add(cand1);
}
if (cnt2 > nums.length/3) {
arr.add(cand2);
}
return arr;
}
}