#169. Majority Element

ยท

1 min read

https://leetcode.com/problems/majority-element/description/?envType=daily-question&envId=2024-02-12

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

    let count = {}, max = Number.NEGATIVE_INFINITY, res = 0

    for (const num of nums) {
        count[num] = (count[num] || 0) + 1

         if (count[num] > max) {
            max = Math.max(max, count[num])
            res = num
        }
    }

    return res
};

Easy question, did it myself but didn't know a loop could do it until today. Thought it had to be two.

ย