219. Contains Duplicate II

题目描述

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 ij,使得 nums [i] = nums [j],并且 ij 的差的绝对值最大为 k

示例 1:

输入: [1,2,3,1], k = 3
输出: true

示例 2:

输入: [1,0,1,1], k = 1
输出: true

示例 3:

输入: [1,2,1], k = 0
输出: false

我的解法——set/hashset+滑动窗口(AC)

  • 存到set中,采用滑动窗口的方法来进行求解,再查询
  • 复杂度O(n),O(k)
  • Beat34%
class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        length = len(nums)
        if(k >= length):
            k = length - 1
        now = set([])
        
        for i in range(length - k):
            if(i != 0):
                now.remove(nums[i - 1])
                if(nums[i + k] in now):
                    return True
                else:
                    now.add(nums[i + k])
            else:
                for j in range(k + 1):
                    if(nums[j] in now):
                        return True
                    else:
                        now.add(nums[j])
        return False