Simple python solution. Hash

  • 1
    class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        :type nums: List[int]
        :type k: int
        :rtype: bool
        length = len(nums)
        dic = {}
        for i in range(length):
            if nums[i] not in dic:
                dic[nums[i]] = (i,i,999999)
                temp = dic[nums[i]]
                if i - temp[1] <= temp[2]:
                    dic[nums[i]] = (temp[1],i,i-temp[1])
        for i in dic.values():
            if i[2] <= k:
                return True
        return False

Log in to reply

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