Leetcode 229. Majority Element II (Medium) (cpp)
Tag: Array
Difficulty: Medium
/*
229. Majority Element II (Medium)
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
Hint:
How many majority elements could it possibly have?
Do you have a better hint? Suggest it!
*/
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> res;
int res1, res2, num1 = 0, num2 = 0;
for (int i = 0; i < nums.size(); i++) {
if (res1 == nums[i]) {
num1++;
} else if (res2 == nums[i]) {
num2++;
} else if (num1 == 0) {
res1 = nums[i];
num1++;
} else if (num2 == 0) {
res2 = nums[i];
num2++;
} else {
num1--;
num2--;
}
}
num1 = 0;
num2 = 0;
for (int i = 0; i < nums.size(); i++) {
if (res1 == nums[i]) {
num1++;
} else if (res2 == nums[i]) {
num2++;
}
}
if (num1 > nums.size() / 3) res.push_back(res1);
if (num2 > nums.size() / 3) res.push_back(res2);
return res;
}
};