Javascript solution-sharing


  • -1
    C

    solution 1:

    /**
     * @param {number[]} nums
     * @return {number}
     */
    var findDuplicate = function(nums) {
        var hashMap = {};
        for(var i=0; i<nums.length; ++i){
            // hashMap[nums[i]] = (hashMap[nums[i]]===undefined)?1:(hashMap[nums[i]]+1);
            if(hashMap[nums[i]]===undefined){
                hashMap[nums[i]] = 1;
            }else{
                hashMap[nums[i]]++;
            }
        }
        for(var attrNm in hashMap){
            if(hashMap[attrNm]>1){
                return Number(attrNm);
            }
        }
        return false;
    };
    

    solution 2:

    /**
     * @param {number[]} nums
     * @return {number}
     */
    var findDuplicate = function(nums) {
        var nums_fb = nums;
        nums_fb.sort();
        for(var i=1; i<nums_fb.length; ++i){
            if(nums_fb[i-1]==nums_fb[i]){
                return nums_fb[i];
            }
        }
    };

Log in to reply
 

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