Python sliding window approach, lower space cost, probably slower?


  • 0
    Q
    class Solution(object):
        
        def containsNearbyDuplicate(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: bool
            """
            if k == 0 or len(nums)<2:
                return False
            queue = collections.deque(nums[:k])
            s = set(queue)
    
            
            if len(s) != len(queue):
                return True
            
            for num in nums[k:]:
                if num in s:
                    return True
                r = queue.popleft()
                s.remove(r)
                queue.append(num)
                s.add(num)
            return False

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.