Skip to content

Commit 3774c76

Browse files
committed
chore: add daily leetcode post 219_translated
1 parent 8fc8e5d commit 3774c76

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
---
2+
title: 219.Existing duplicate elements II Hash table graphics
3+
date: '2024.01.01 0:00'
4+
categories:
5+
- - Python
6+
- Hash table
7+
- - solved
8+
- answer
9+
tags:
10+
- - Python
11+
- - solved
12+
abbrlink: 16b0e9f1
13+
---
14+
15+
# Thought
16+
17+
This question was done on the phone at first,直接用的是双Hash table,An element,One depositindex,When a certain element exceeds2Judging whether there are two of them when they areindexSubtission is equal tokCase。So the complexity of time is`O(n^3)`
18+
19+
# Code:
20+
21+
```python
22+
class Solution:
23+
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
24+
hash_1={}
25+
hash_2={}
26+
for index, i in enumerate(nums):
27+
if i not in hash_1:
28+
hash_1[i] = 1
29+
hash_2[i] = [index]
30+
else:
31+
hash_1[i] += 1
32+
hash_2[i].append(index)
33+
for i in hash_1:
34+
if hash_1[i] >= 2:
35+
for j in range(len(hash_2[i])):
36+
for m in range(j + 1, len(hash_2[i])):
37+
if abs(hash_2[i][j]-hash_2[i][m]) <= k:
38+
return True
39+
return False
40+
```
41+
42+
look[@Gongshui Sanye](/u/ac_oier)Gongshui Sanye的解法后,Only think of,这道题的目的是为了练习双指针在Hash table中的应用,TAThe original words are sorting the meaning:Whether the existence does not exceed k+1k + 1k+1 window,window内有相同元素。
43+
```
44+
#Sort out the meaning:Whether the existence does not exceed k+1k + 1k+1 window,window内有相同元素。
45+
class Solution:
46+
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
47+
n = len(nums)
48+
s = set()
49+
for i in range(n):
50+
if i > k:
51+
s.remove(nums[i - k - 1])
52+
if nums[i] in s:
53+
return True
54+
s.add(nums[i])
55+
return False
56+
```

0 commit comments

Comments
 (0)