🔗LC169 🟢 Easy 🧩 Pattern – Arrays and Hashmap
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.
Example
Input: nums = [3,2,3]
Output: 3
Input: nums = [2,2,1,1,1,2,2]
Output: 2Code language: JavaScript (javascript)Solution
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function (nums) {
const tracker = {};
const half = nums.length / 2;
for (let i = 0; i < nums.length; i++) {
const current = nums[i];
tracker[current] = (tracker[current] || 0) + 1;
if (tracker[current] > half) {
return current;
}
}
};
console.log(majorityElement([1, 2, 3, 4, 5, 5, 5, 5, 5]));
// Output: 5Code language: JavaScript (javascript)