Majority Element II
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 m = 0, n = 0, cm = 0, cn = 0; for (size_t i = 0; i < nums.size(); i++) { if (nums[i] == m) cm++; else if (nums[i] == n) cn++; else if (cm == 0) { m = nums[i]; cm++; } else if (cn == 0) { n = nums[i]; cn++; } else { cn--; cm--; } } cm = 0; cn = 0; for (auto num : nums) { if (num == m) { cm++; } else if (num == n) { cn++; } } if (cm > nums.size() / 3) res.push_back(m); if (cn > nums.size() / 3) res.push_back(n); return res; } };