[easy][Array][HashTable]219.Contains Duplicate II

weixin_34249678發表於2017-11-24

原題是:

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.

思路是:

陣列中用到hash往往跟強調元素的index有關。這些Index往往是固定不變的。

程式碼是:

class Solution:
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        if not nums or k < 1:
            return False
        dicts = {}
        for i,num in enumerate(nums):
            if num not in dicts:
                dicts[num] = i
            else:
                if i - dicts[num] <= k:
                    return True
                else:
                    dicts[num] = i
        
        return False

相關文章