【LEETCODE】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 difference between i and j is at most k.


参考:

http://bookshadow.com/weblog/2015/05/29/leetcode-contains-duplicate-ii/




class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        
        hashdict=dict()
        
        for x in range(len(nums)):
            
            idx=hashdict.get(nums[x])    #得到nums[x]在hashdict中保存的在nums中出现过的位置
            
            if idx>=0 and x-idx<=k:      #如果idx是None,说明nums[x]还没有出现过,则在hashdict中保存数及位置
                return True              #如果出现过了,则idx为nums[x]第一次出现的位置,x为当前即第二次出现的位置,且x>idx
            hashdict[nums[x]]=x
            
        return False


你可能感兴趣的:(LeetCode,python)