Simple solution by using a hashmap


  • 0
    /**
     * Memo: Use a map to record latest index of each element, and check if the duplicate is within K elements away
     * Complex: O(n)
     * Runtime: 128ms
     * Tests: 19 test cases passed
     * Rank: B
     * Updated: 2015-11-11
     */
    var containsNearbyDuplicate = function(nums, k) {
        var map = Object.create(null);
        for (var i = 0; i < nums.length; i++) {
            if (map[nums[i]] >= 0 && i - map[nums[i]] <= k) return true;
            map[nums[i]] = i;
        }
        return false;
    };

Log in to reply
 

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