Problem
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.
Definition
Majority Element: If an element appears more than n/2 times in array where n is the size of the array.
Examples
Example 1
|
|
Example 2
|
|
Constraints
n == nums.length
1 <= n <= 5 * 10^4
-10^9 <= nums[i] <= 10^9
Follow up
- Could you solve the problem in linear time and in
O(1)
space? - What if we cannot assume that majority element always exists in an array.
Solution
This post goes through general solution - but we already have best solution: Majority Element - Boyer–Moore majority vote algorithm
Method 1 - Brute Force or Naive
Use nested for loops and count each element and if count>n/2 for each element. Time Complexity: O(n^2)
|
|
Method 2 - Hashmap
- Store the count of each element in Hash map.
- Iterate through hash map and check if any element has count >n/2
Time Complexity: O(n), Space Complexity: O(n)
|
|
Method 3 - Sorting
We can sort the array first, which takes time of nlog(n). Then scan once to find the longest consecutive substrings.
|
|
Method 4 - Sorting but Much Simpler
Thanks to SK. His/her solution is much efficient and simpler. Since the majority always take more than a half space, the middle element is guaranteed to be the majority. Sorting array takes nlog(n). So the time complexity of this solution is nlog(n). Cheers!
|
|