-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy path219_Contains_Duplicate_II.py
36 lines (34 loc) · 1.07 KB
/
219_Contains_Duplicate_II.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution(object):
# def containsNearbyDuplicate(self, nums, k):
# """
# :type nums: List[int]
# :type k: int
# :rtype: bool
# """
# check = {}
# for i in range(len(nums)):
# try:
# check[nums[i]].append(i)
# except:
# check[nums[i]] = [i]
# # hash all value with its index
# # then check the difference between indexes under the same value
# for _, v in check.items():
# if len(v) >= 2:
# pos = 0
# while pos + 1 < len(v):
# if v[pos + 1] - v[pos] <= k:
# return True
# pos += 1
# return False
def containsNearbyDuplicate(self, nums, k):
# check k interval
check = set()
for i in range(len(nums)):
if i > k:
check.remove(nums[i - k - 1])
if nums[i] in check:
return True
else:
check.add(nums[i])
return False