Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Follow-up: Could you solve the problem in linear time and in O(1) space?
The brute-force method checks each element in the array and counts how many times it appears. If any element occurs more than n/2 times (where n is the length of the array), that element is the majority element.
This approach is simple to understand but inefficient because it performs a full scan for every element.
We can optimize the brute force approach by using a HashMap to store the frequency of each element.
Traverse the array, and increment the counter for each element encountered. The element with a frequency greater than n/2 will be the majority element.
If we sort the array, all identical elements naturally group together. Since the majority element appears more than n/2 times, it must occupy the entire middle region of the sorted array.
That means the element at index n/2 will always be the majority element.
Input:
After sorting:
The Boyer-Moore Voting Algorithm efficiently finds the majority element in linear time.
It maintains:
As you scan:
count == 0, adopt the current number as the new candidate.candidate, increment count; otherwise, decrement it.If a true majority exists, this process guarantees the final candidate is that majority.
Think cancellation. Pair up elements as we scan:
candidate, we “cancel” one occurrence of the candidate with that different value by doing count--.count, effectively “uncanceling” or reinforcing the candidate.If there truly is a majority element M (appears more than ⌊n/2⌋ times), then:
M element can be paired with at most one M for cancellation.M occurs strictly more than all others combined, you cannot cancel all of the Ms. There will be a surplus of Ms left unpaired.M.