JavaScript Solution Using Map


  • 0
    I
    /**
     * @param {number[]} nums
     * @param {number} k
     * @return {boolean}
     */
    var containsNearbyDuplicate = function(nums, k) {
        
        var mapObj = {},
            cur,
            numsLen = nums.length;
        
        for (cur = 0; cur < numsLen; cur++) {
            if (mapObj.hasOwnProperty(nums[cur])) {
                if (cur - mapObj[nums[cur]] <= k) {
                    return true;
                } 
                else {
                    mapObj[nums[cur]] = cur;
                }
            }
            else {
                mapObj[nums[cur]] = cur;
            }
        }
        
        return false;
        
    };
    

    I'm using the map to store the index of current element in the array, when find the element more than one time, calculate the difference between the current index and stored index, if satisfy the requirement return true, else replace the value in the map.


Log in to reply
 

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