본문 바로가기
CS/algorithm

[LeetCode] 169. Majority Element

by 빠니몽 2024. 6. 27.

06.27.2024

 

1. Problem

Majority Element Problem Description

2. My Code

/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    var obj = Object();
    nums.forEach((e) => {
        if (obj[e]) obj[e]++;
        else obj[e] = 1;
    });
    
    let max = 0;

    Object.entries(obj).forEach((pair) => {
        const standard = parseInt(nums.length / 2);
        if (pair[1] > standard) max = pair[0];
    });

    return max;
};

 

3. For Follow-Up

Though I haven't tried this problem with the follow-up rule, you can use Boyer-Moore Majority Vote algorithm.

I am not sure of the popularity or the necessity of this algorithm but just in case anyone wants to try, you can search for it.