Boyer-Moore Majority Vote Algorithm
Today’s LeetCode daily challenge requires finding a dominant item that appears more than half the time in an array.
I used a hash map to count each item and track the most frequent one during this process.
This results in O(N*log N) time complexity and O(N) space complexity.
After I applied my solution, I found that most other solutions were much faster than mine.
They all used a simple algorithm to find the dominant item - Boyer-Moore Majority Vote Algorithm:
def majority_element(nums): |
If you know that there is a dominant item appears more than half the time in an array, this algorithm will find it in O(N) time and O(1) space.
Amazing!
