avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

219.Existing duplicate elements II Hash table graphics

  2024-01-01        
字数统计: 254字   |   阅读时长: 1min

Thought

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 isO(n^3)。

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
hash_1={}
hash_2={}
for index, i in enumerate(nums):
if i not in hash_1:
hash_1[i] = 1
hash_2[i] = [index]
else:
hash_1[i] += 1
hash_2[i].append(index)
for i in hash_1:
if hash_1[i] >= 2:
for j in range(len(hash_2[i])):
for m in range(j + 1, len(hash_2[i])):
if abs(hash_2[i][j]-hash_2[i][m]) <= k:
return True
return False

look@Gongshui SanyeGongshui 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内有相同元素。

1
2
3
4
5
6
7
8
9
10
11
12
#Sort out the meaning:Whether the existence does not exceed k+1k + 1k+1 window,window内有相同元素。
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
n = len(nums)
s = set()
for i in range(n):
if i > k:
s.remove(nums[i - k - 1])
if nums[i] in s:
return True
s.add(nums[i])
return False
  • Python
  • solved

扫一扫,分享到微信

微信分享二维码
217. Existing duplicate elements C++/Python3
221Maximum square
目录
  1. 1. Thought
  2. 2. Code:

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号