majority-element
Problem
Problem Description
Solution
Solution 1 -- HashMap
Using HashMap to store each element with its frequency as pair.
iterate through array nums, add each number and its frequency into map
after add into map, check whether current element frequency already greater than [n/2],
if already, then terminate return current element.
if not, continue.
since it is already assumed that array is non-empty, and always has majority element exist, so during iterate, majority element must find.
Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(N)
N - length of array nums
Code
Solution 2 -- Boyer-Moor voting algorithm
Assume that we maintain a candidate and count, iterate through array nums:
We check count, if we found count == 0, reset candidate = num (current element)
at the same time, we check current element num == candidate,
if num == candidate, then count + 1;
if num != candidate, then count - 1
at last, remain candidate is majority element.
Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(1)
N - the length of array nums
Code -- Boyer-Moor voting algorithm
Last updated