- Contains Duplicate II
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
my thoughts:
1. use a set to keep track of the n seen in the k window, update the set by adding the new n and removing the oldest n.
my solution:
**********62ms
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if k <= 0:
return False
l = len(nums)
s = set()
i = 0
while i<=k and i<l:
if nums[i] in s:
return True
else:
s.add(nums[i])
i += 1
while i<l:
s.remove(nums[i-k-1])
if nums[i] in s:
return True
else:
s.add(nums[i])
i += 1
return False
my comments:
from other ppl's solution:
python's set and dict conversion are unblievable cheap.
1. brutal force is faster, 35ms:
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
dict1 = {}
for i, v in enumerate(nums):
if v not in dict1:
dict1[v] = i
else:
if i - dict1[v] <= k:
return True
else:
dict1[v] = i
return False