Majority Element
Array
Easy
Given an array of sizen, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Example 2:
Solution
Approach 1: HashMap
We can use a HashMap that maps elements to counts in order to count occurrences in linear time by looping over nums. Then, we simply return the key with maximum value.
Time complexity: O(n)
Space complexity : O(n)
Approach 2: Sorting
If the elements are sorted in monotonically increasing (or decreasing) order, the majority element can be found at index ⌊ n / 2 ⌋ (and ⌊ n / 2 ⌋ + 1, incidentally, if n is even).
Time complexity : O(nlgn) Sorting the array costs O(nlgn) time in Python and Java, so it dominates the overall runtime.
Space complexity : O(1) or (O(n)) We sorted nums in place here - if that is not allowed, then we must spend linear additional space on a copy of nums and sort the copy instead.
Approach 3: Boyer-Moore Voting Algorithm
If we had some way of counting instances of the majority element as +1 and instances of any other element as −1, summing them would make it obvious that the majority element is indeed the majority element.
Complexity Analysis
Time complexity :O(n)
Boyer-Moore performs constant work exactlynntimes, so the algorithm runs in linear time.
Space complexity :O(1)
Boyer-Moore allocates only constant additional memory.
Reference
Last updated