找出現次數 > ⌊n/3⌋ 的元素,最多存在 2 個。通用化:找 > ⌊n/k⌋ 的元素,最多 k-1 個。
cand1, cand2 及其計數 cnt1, cnt2。public List<Integer> majorityElement(int[] nums) {
int cand1 = 0, cand2 = 0, cnt1 = 0, cnt2 = 0;
for (int n : nums) {
if (cnt1 > 0 && n == cand1) cnt1++;
else if (cnt2 > 0 && n == cand2) cnt2++;
else if (cnt1 == 0) { cand1 = n; cnt1 = 1; }
else if (cnt2 == 0) { cand2 = n; cnt2 = 1; }
else { cnt1--; cnt2--; }
}
// 驗證
cnt1 = cnt2 = 0;
for (int n : nums) {
if (n == cand1) cnt1++;
else if (n == cand2) cnt2++;
}
List<Integer> res = new ArrayList<>();
if (cnt1 > nums.length / 3) res.add(cand1);
if (cnt2 > nums.length / 3) res.add(cand2);
return res;
}
此算法源自 Boyer-Moore 多數投票擴展,是面試高頻考點,掌握即可秒殺「超過 1/k」類問題。