JS solution using a map


  • 0
    N
    // https://leetcode.com/problems/contains-duplicate-ii/
    
    var Cache = Object.create(null);
    
    Cache.get = function(k) {
        return this[k];
    };
    
    Cache.set = function(k, v) {
        this[k] = v;
    };
    
    Cache.has = function(k) {
        return this[k] != null;
    };
    
    /**
     * @param {number[]} nums
     * @param {number} k
     * @return {boolean}
     */
    var containsNearbyDuplicate = function(nums, k) {
        var map = Object.create(Cache);
    
        return nums.some(function(num, idx) {
            if (map.has(num)) {
                var old_idx = map.get(num);
                if (Math.abs(old_idx - idx) <= k) {
                    return true;
                }
            }
    
            map.set(num, idx);
        });
    };

Log in to reply
 

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