Contains Duplicate II——Array

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dic = {}
        for i in range(len(nums)):
            if nums[i] not in dic:
                dic.setdefault(nums[i],i)
            elif abs(dic[nums[i]] - i) <= k:
                return True 
            else:
                dic[nums[i]] = i
        return False

 

猜你喜欢

转载自qu66q.iteye.com/blog/2316656