美文网首页
[easy][Array][HashTable]219.Cont

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

作者: 小双2510 | 来源:发表于2017-11-24 13:58 被阅读0次

原题是:

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

相关文章

网友评论

      本文标题:[easy][Array][HashTable]219.Cont

      本文链接:https://www.haomeiwen.com/subject/juzxbxtx.html