[LeetCode][Python]212. Contains Duplicate 2

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

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容