169. Majority Element
Intuition
Given an list of numbers of size n, return the element that appears more than ⌊n / 2⌋ times.
- You may assume that the majority element always exists in the array.
- There is only one majority element in the given array.
- An array of Integer
n == nums.length1 <= n <= 5 * 10^4-10^9 <= nums[i] <= 10^9
Solution 1 HashMap
Approach
- Step 1: Create a hash map
resto store the stats of elements in the given array - Step 2: During the loop iteration, for
nums[i]- If
resdoes not contain a keynums[i], add it and set its value as the number of appearance, initializing as 1. - If
rescontains a keynums[i], update its number of appearance.
- If
- Step 3: When we encounter a key whose value is greater than
⌊n / 2⌋, return this key.
Complexity
- Time complexity: \(O(n)\)
- Space complexity: \(O(k)\) for k distinct element in array
Code
Solution 2 "Vote"
Approach
There is a "clever" approach to solve this problem,
- Firstly, we set
nums[0]as candidateres, and initialize the candidate's votecountto 1. - When we encounter the same number as
resis , the votecount++, otherwise the votecount--. - When the vote
countis 0, change the candidate and reset the votecountto 1. - After traversing the array, our candidate number
resis the final answer.
Why? This is equivalent to each ‘majority element’ canceling out with other elements in pairs. By the end, there will definitely be at least one ‘majority element’ remaining.
For this solution, as we simply traverse the array without implementing any other extra data structure, we optimize the space complexity!
Reference: 🔗 Boyer-Moore Majority Vote Algorithm
Complexity
- Time complexity: \(O(n)\)
- Space complexity: \(O(1)\)