`

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics