219.Existing duplicate elements II Hash table graphics
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:
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 Falselook@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内有相同元素。
#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贡献者
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0
1828. Statistics the number of a circle mid -point One question daily
LeetCode 1828. 统计一个圆中点的数目 题解 — 使用欧几里得距离公式计算每个点与圆心的距离,判断是否小于等于半径,时间复杂度 O(n^2)。关键技巧是直接遍历所有点与所有圆,无需优化。适合正在刷 LeetCode 每日一题、入门数学类模拟题的求职者和算法初学者。
2241. 设计 ATM 机器
LeetCode 2241. 设计 ATM 机器 题解 — 使用贪心算法模拟 ATM 取款与存款逻辑,核心技巧是反向遍历面额数组(500→20)并利用哈希表或数组记录各面额钞票数量,优先使用大面额钞票。适合准备系统设计面试或刷 LeetCode 中等模拟题的 CS/AI 求职者。