229. Majority Element II**

​https://leetcode.com/problems/majority-element-ii/​

题目描述

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 229. Majority Element II**_数组 space.

Example 1:

Input: [3,2,3]
Output: [3]

Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]

解题思路

承接 ​​169. Majority Element*​​​, 是该题的加强版. 解决思路仍然是使用投票法, 但是现在候选人变成了两个. 因为对于一个大小为 ​​n​​​ 的数组, 最多只有两个元素的个数超过 ​​⌊ n/3 ⌋​​.

C++ 实现 1

分别对两个候选进行投票, 如果当前候选人的票数为 0, 那么就要更新候选人和票数. 待两个候选人求出来之后, 再遍历一次数组统计两个候选人的票数是否超过 ​​⌊ n/3 ⌋​​.

lass Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int candidate1, candidate2;
int votes1 = 0, votes2 = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == candidate1) votes1 ++;
else if (nums[i] == candidate2) votes2 ++;
else if (votes1 == 0) candidate1 = nums[i], votes1 ++;
else if (votes2 == 0) candidate2 = nums[i], votes2 ++;
else votes1 --, votes2 --; // 注意是逗号表达式, 写成一行的话
}
int count1 = 0, count2 = 0;
// 判断两个候选的 vote 是不是真的超过了 1/3
for (int i = 0; i < nums.size(); ++i) {
count1 += nums[i] == candidate1 ? 1 : 0;
count2 += nums[i] == candidate2 ? 1 : 0;
}
int n = nums.size();
vector<int> res;
if (count1 > n / 3) res.push_back(candidate1);
// 以防两个候选人是一样的
if (count2 > n / 3 && candidate1 != candidate2) res.push_back(candidate2);
return res;
}
};