美文网首页Leetcode
219. Contains Duplicate II

219. Contains Duplicate II

作者: oo上海 | 来源:发表于2016-08-01 12:03 被阅读15次

    219. Contains Duplicate II

    题目:
    https://leetcode.com/problems/contains-duplicate-ii/

    难度:

    Easy

    经过了Contains Duplicate的考验,用hash table(也叫dictionary)来存,这个元素还没出现过,就放hash table,如果出现了,计算相邻距离,小于等于k则return true,否则更新hash table中元素的位置,

    我用的sort

    class Solution(object):
        def containsNearbyDuplicate(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: bool
            """
            if len(nums) < 2 : return False
            lookup = {}
            for i in range(len(nums)):
                if nums[i] not in lookup:
                    lookup[nums[i]] = i
                else:
                    if i - lookup[nums[i]] <= k :
                        return True
                    lookup[nums[i]] = i
            return False
    

    相关文章

      网友评论

        本文标题:219. Contains Duplicate II

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