DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Majority Element

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

    for(let i=0; i<nums.length; i++){
        if(map[nums[i]]){
            map[nums[i]] = map[nums[i]] +1;
        }else {
             map[nums[i]] = 1;
        }
    };

    let max =0;
    let maxKey = 0;
    for(const key in map){
        let value = map[key];
        if(max < value){
            max = value;
            maxKey = key;
        } 
    }
return maxKey;
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)