Majority Element
Problem
Input: nums = [3,2,3] Output: 3Input: nums = [2,2,1,1,1,2,2] Output: 2
Pseudocode
Solution
Time and Space Complexity
Time
Space
Last updated
Input: nums = [3,2,3] Output: 3Input: nums = [2,2,1,1,1,2,2] Output: 2
Last updated
make a map of unique numbers and the number of occurances, return majority element immediately if > n / 2 is foundvar majorityElement = function (nums) {
const len = nums.length;
const map = {};
for (let i = 0; i < len; i++) {
if (!map[nums[i]]) {
map[nums[i]] = 0;
}
map[nums[i]]++;
if (map[nums[i]] > len / 2) {
return nums[i];
}
}
};