[LeetCode][Python]212. Contains

2017-05-03  本文已影响33人  bluescorpio

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

上一篇 下一篇

猜你喜欢

热点阅读