-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0219.Contains_Duplicate_II.py
More file actions
53 lines (39 loc) Β· 1.17 KB
/
0219.Contains_Duplicate_II.py
File metadata and controls
53 lines (39 loc) Β· 1.17 KB
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
"""
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
0 <= k <= 105
"""
#hash
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
posDict = collections.defaultdict(int)
for i, num in enumerate(nums):
if num in posDict:
if i - posDict[num] <= k:
return True
posDict[num] = i
return False
#sliding window
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
numSet = set()
j = 0
for i in range(len(nums)):
while j < len(nums) and j - i <= k:
if nums[j] in numSet:
return True
numSet.add(nums[j])
j += 1
numSet.remove(nums[i])
return False