How to improve my JavaScript code?


  • 0
    E
    var majorityElement = function(nums) {
        var map = {};
        var maj = Math.ceil(nums.length / 2);
        for(var i in nums){
            if(map[nums[i]] === undefined){
                map[nums[i]] = 0;
            }
            map[nums[i]]++;
            if(map[nums[i]] >= maj){
                return nums[i];
            }
        }
    };
    

    is it a O(n) algorithm? why it take more than 100ms to finish all test cases? how to improve it ?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.