Python solution using dict


  • 3
    T
    class Solution:
        # @param {integer[]} nums
        # @param {integer} k
        # @return {boolean}
        def containsNearbyDuplicate(self, nums, k):
            d = {}
            for i in range(len(nums)):
                if nums[i] in d:
                    j = d[nums[i]]
                    if i-j<=k:
                        return True
                d[nums[i]] = i
            return False

  • 5
    M
    class Solution:
        # @param {integer[]} nums
        # @param {integer} k
        # @return {boolean}
        def containsNearbyDuplicate(self, nums, k):
            
            d = {}
            for i, v in enumerate(nums):
                if v in d and i - d[v] <=k:
                    return True
                else:
                    d[v] = i
            return False
    

    You can use enumerate to make index


Log in to reply
 

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