Skip to main content

Leetcode - 169. Majority Element

· One min read

https://leetcode.com/problems/majority-element/

Solution 1

/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function (nums) {
const element = {};

for (const num of nums) {
if (element[num]) {
element[num]++;
} else {
element[num] = 1;
}
}

let max = 0;
let targetNum = '';

for (let e in element) {
if (element[e] > max) {
max = element[e];
targetNum = e;
}
}

return Number(targetNum);
};