Solution to LeetCode 219 Contains Duplicate II.
LeetCode 219
Contains Duplicate II (Easy). [link]
- HashTable. 1) if there is a number in
hash
such thati-j <= k
, return True. 2) if not inhash
, add its index to thehash
. Time complexity O(N). Space complexity O(N).
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
hash = {}
for i, num in enumerate(nums):
if num in hash and i - hash[num] <= k:
return True
hash[num] = i
return False
- Sliding window. Find a sliding window with size < (k+1) such that it contains duplicated numbers. Time complexity O(N). Space complexity O(K).
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
s = set() # sliding window
for i, num in enumerate(nums):
if i > k:
s.remove(nums[i - k - 1])
if num in s:
return True
s.add(num)
return False
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
hash = {}
start, end = 0, 0 # sliding window
for end in range(len(nums)):
if nums[end] not in hash:
hash[nums[end]] = 1
else:
return True
if end - start + 1 > k:
del hash[nums[start]]
start += 1
return False