所以我们用两个变量 cand1 和 cand2 表示两个候选人,cnt1 和 cnt2 表示两个候选人数量。那么如果两个候选人有一个和当前数 x 相同,对应的数量就加一。否则的话如果如果有某个候选人为空,就让 x 顶替成为新的候选人。否则的话就说明两个候选人都有,并且 x 和它俩都不相同,那么就同时删除三个不同的数,也就是两个候选人数量各减一,同时删去 x 。
最后判断两个候选人数量是否超过了 1/3 就行了。
这里关键点就在于,每次删除三个不同的数,判断最后剩下的数是否符合题意就行了。
代码
c++
classSolution { public: vector<int> majorityElement(vector<int>& nums){ int n = nums.size(); int cand1 = 0, cand2 = 0, cnt1 = 0, cnt2 = 0; for (auto x : nums) { if (cand1 == x) { cnt1++; } elseif (cand2 == x) { cnt2++; } elseif (!cnt1) { cand1 = x; cnt1++; } elseif (!cnt2) { cand2 = x; cnt2++; } else { cnt1--; cnt2--; } } cnt1 = cnt2 = 0; for (auto x : nums) { if (x == cand1) cnt1++; elseif (x == cand2) cnt2++; } vector<int> res; if (cnt1 > n/3) res.push_back(cand1); if (cnt2 > n/3) res.push_back(cand2); return res; } };
python
classSolution: defmajorityElement(self, nums: List[int]) -> List[int]: n = len(nums) cand1, cand2, cnt1, cnt2 = 0, 0, 0, 0 for x in nums: if cand1 == x: cnt1 += 1 elif cand2 == x: cnt2 += 1 elif cnt1 == 0: cand1 = x cnt1 = 1 elif cnt2 == 0: cand2 = x cnt2 = 1 else: cnt1 -= 1 cnt2 -= 1 cnt1 = cnt2 = 0 for x in nums: if x == cand1: cnt1 += 1 elif x == cand2: cnt2 += 1 res = [] if cnt1 > n//3: res.append(cand1) if cnt2 > n//3: res.append(cand2) return res