Description:
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.
Solution:
Time Complexity : O(n)
Space Complexity: O(n)
// Use a hashmap to save the count of each element
// Return the first number whose count is equal to the majority
var majorityElement = function(nums) {
// Define the majority number to reach
const majority = Math.round(nums.length / 2)
const map = {}
for(let i = 0; i<nums.length; i++){
const cur = nums[i]
// Increment the count of each number in the hashmap
map[cur] = (map[cur] || 0) + 1
// Return the first number whose count is equal to the majority
if(map[cur]===majority) return cur;
}
};
Top comments (0)