majority-element
Last updated
Was this helpful?
Last updated
Was this helpful?
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.
Time Complexity: O(N)
Space Complexity: O(N)
N - length of array nums
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.
Time Complexity: O(N)
Space Complexity: O(1)
N - the length of array nums