Challenge Description
Given an array of size n, 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:
|
Naive Solution
Iterate over all the elements in array, use a unordered_map
to store the counts of current element, when one element’s count > size/2
, it’s OK to break the loop and return the element.
Time complexity: $O(N)$.
|
Approach with sorting
If we sort the array, the element at index size/2 will be the answer.
Time complexity: $O(NlogN)$.
|
Join my Email List for more insights, It's Free!😋