Javascript, solution-sharing, easy to understand


  • 0
    C
    [javascript]
    
    /**
     * step 1: Definition of an object // var myHashMap = {};
     * step 2: first time // Because it is an empty object, myHashMap[nums[i]]===undefined; if(myHashMap[nums[i]]===undefined) { myHashMap[nums[i]]=i; }
     * step 3: second time // myHashMap[nums[i]]!==undefined; if(i-myHashMap[nums[i]]<k) { return true; } else { myHashMap[nums[i]]=i; }
     */
    var containsNearbyDuplicate = function(nums, k) {
        var myHashMap = {};
        for(var i=0; i<nums.length; i++){
            if(myHashMap[nums[i]]!==undefined && (i-myHashMap[nums[i]])<=k){
                // console.log("i="+i+"; myHashMap["+nums[i]+"]="+myHashMap[nums[i]]+";");
                return true;
            }else{
                myHashMap[nums[i]] = i;
            }
            // console.log(myHashMap);
        }
        return false;
    };

Log in to reply
 

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