My javascript solution in hash


  • 0
    E
    var majorityElement = function(nums) {
        var hash = {};
        for (var i = 0;i < nums.length;i++){
            hash[nums[i]] = 0;
        }
        for (var i = 0;i < nums.length;i++){
            hash[nums[i]] ++;
        }
        for (var name in hash){
            
            if(hash[name] > (nums.length/2)){
                var num = parseInt(name);
                return num;
            }
                
        }
    };

  • 1
    D
     * @param {number[]} nums
     * @return {number}
     */
    var majorityElement = function(nums) {
        var letterHash = {};
        for (var x = 0; x < nums.length; x++) {
          if (letterHash[nums[x]]) {
            letterHash[nums[x]] += 1;
          } else {
            letterHash[nums[x]] = 1; 
          }
        }
        for (letter in letterHash) {
            if (letterHash[letter] > nums.length / 2) {
                return parseInt(letter);
            }
        }   
    }
    

    This is is a similar solution but reduces it by one loop


  • 0
    E

    @dewolf oh,my stupid solution,thx


  • 0
    T
    /**
     * @param {number[]} nums
     * @return {number}
     */
    var majorityElement = function(nums) {
        var letterHash = {};
        for (var i = 0; i < nums.length; i++) {
            letterHash[nums[i]]?letterHash[nums[i]] ++:letterHash[nums[i]] = 1;
            if (letterHash[nums[i]] > nums.length / 2) {
                return nums[i];
            }
        }
    };
    

    excuse for referencing your solution and a little change


Log in to reply
 

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