[easy][Array][HashTable]219.Cont

2017-11-24  本文已影响0人  小双2510

原题是:

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
上一篇 下一篇

猜你喜欢

热点阅读