712100. Majority Element II
Majority Element II Slug: majority-vote Difficulty: Medium Id: 712100 Topic Tags: Arrays
Summary
The Majority Element II problem is about finding all elements that appear more than n/2 times in an array, where n is the size of the array. This problem involves using a technique called Boyer-Moore Voting Algorithm to find these majority elements.
Detailed Explanation
To solve this problem, we will use the Boyer-Moore Voting Algorithm. The algorithm works by essentially maintaining a counter for the majority element. If the count becomes zero, we update the candidate and reset the count.
Here is the step-by-step breakdown of the solution:
- Initialize the count and candidate to 0.
- Iterate through the array:
- If the current element matches the candidate, increment the count.
- If the current element does not match the candidate, decrement the count.
- If the count becomes zero, update the candidate and reset the count.
After the algorithm finishes, if the count is greater than 0, then the candidate is a majority element. However, this algorithm may return a false positive (i.e., an element that appears less than n/2 times) as the majority element. To fix this, we need to check each element in the array to see if it indeed occurs more than n/2 times.
Time complexity: O(n), where n is the size of the array. Space complexity: O(1).
Optimized Solutions
Java
public class Solution {
public List<Integer> majorityElements(int[] nums) {
int count = 0;
int candidate = 0;
for (int num : nums) {
if (num == candidate) {
count++;
} else {
count--;
if (count == 0) {
candidate = num;
count = 1;
}
}
}
List<Integer> result = new ArrayList<>();
int occurrences = 0;
for (int num : nums) {
if (num == candidate) {
occurrences++;
}
}
if (occurrences > nums.length / 2) {
result.add(candidate);
} else {
candidate = 0;
count = 0;
for (int num : nums) {
if (num == candidate) {
count++;
} else {
count--;
if (count == 0) {
candidate = num;
count = 1;
}
}
}
occurrences = 0;
for (int num : nums) {
if (num == candidate) {
occurrences++;
}
}
if (occurrences > nums.length / 2) {
result.add(candidate);
} else {
for (int num : nums) {
int count1 = 0;
int candidate1 = 0;
for (int i : nums) {
if (i == num) {
count1++;
} else if (count1 > 0) {
count1--;
} else if (i == candidate1) {
count1++;
candidate1 = num;
}
}
if (count1 > nums.length / 2) {
result.add(num);
}
}
}
}
return result;
}
}