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
        """
        m = {}
        for i in range(len(nums)):
            if (m.has_key(nums[i]) and i-m[nums[i]]<=k):
                return True
            else:
                m[nums[i]] = i
        return False

 

posted @ 2017-10-27 14:46  bernieloveslife  阅读(121)  评论(0编辑  收藏  举报