219. Contains Duplicate II

219. Contains Duplicate II

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 absolute 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={}
        ans=False
        for i,n in enumerate(nums):
            if n in dic:
                if abs(dic[n]-i)<=k:
                    ans=True
                    break
                else:dic[n]=i
            else:
                dic[n]=i
        
        return ans
        

 

posted @ 2017-01-21 23:39  rocksolid  阅读(141)  评论(0编辑  收藏  举报