美文网首页
[LeetCode][Python]212. Contains

[LeetCode][Python]212. Contains

作者: bluescorpio | 来源:发表于2017-05-03 22:56 被阅读33次

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array s;uch that nums[i] = nums[j]and the absolute difference between i and j is at most k.

思路:

使用一个map来存放元素,enumerate函数用于遍历序列中的元素以及它们的下标。当元素没在map中,组成一个item,index对。继续遍历。如果发现元素在map中,然后两者之差小于k,则说明存在这样的元素对。

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        d = {}
        for index, item in enumerate(nums):
            if item in d and index - d[item] <= k:
                return True
            else:
                d[item] = index
        print d
        return False

相关文章

网友评论

      本文标题:[LeetCode][Python]212. Contains

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