-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContainsDuplicateII.py
54 lines (52 loc) · 1.4 KB
/
ContainsDuplicateII.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
1 3 4 2 3 1
"""
table = {}
for i in range(len(nums)):
if nums[i] in table:
if len(table[nums[i]]) == 1:
table[nums[i]].append(i)
else:
if i - table[nums[i]][1] < table[nums[i]][1] - table[nums[i]][0]:
table[nums[i]] = [table[nums[i]][1], i]
else:
table[nums[i]] = [i]
for n in table:
if len(table[n]) == 2 and table[n][1] - table[n][0] <= k:
return True
return False
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
window = set()
for i in range(len(nums)):
if i > k:
window.remove(nums[i-k-1])
if nums[i] in window:
return True
window.add(nums[i])
return False
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
table = {}
for i in range(len(nums)):
if nums[i] in table:
j = table[nums[i]]
if i - j <= k:
return True
table[nums[i]] = i
return False