Leetcode 229. Majority Element II
Given an integer array of size n
, find all elements that appear more than ⌊ n/3 ⌋ times.
Input: nums = [3,2,3]
Output: [3]
Input: nums = [1]
Output: [1]
Input: nums = [1,2]
Output: [1,2]
Constraints:
1 <= nums.length <= 5 * 10^4
-10^9 <= nums[i] <= 10^9
To solve this problem, we can use a modified version of the Boyer-Moore Voting Algorithm which is originally used for finding the majority element (i.e., an element that appears more than ⌊ n/2 ⌋ times). For this problem, we need to find elements that appear more than ⌊ n/3 ⌋ times.
Key steps are:
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> majorityElement(vector<int>& nums) {
int n = nums.size();
if (n == 0) return {};
int candidate1 = 0, candidate2 = 1; // Initialize two different candidates
int count1 = 0, count2 = 0;
// First pass to find possible candidates
for (int num : nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
} else if (count1 == 0) {
candidate1 = num;
count1 = 1;
} else if (count2 == 0) {
candidate2 = num;
count2 = 1;
} else {
count1--;
count2--;
}
}
// Second pass to check if the candidates actually have the required count
count1 = 0;
count2 = 0;
for (int num : nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
}
}
vector<int> result;
if (count1 > n / 3) {
result.push_back(candidate1);
}
if (count2 > n / 3) {
result.push_back(candidate2);
}
return result;
}
The solution involves two passes through the array:
n
is the length of the array.Overall, the time complexity is O(n).
The space complexity is O(1) because we use a constant amount of extra space beyond the input array.
This solution is efficient and meets the constraints specified in the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?