leetcode219. Contains Duplicate II

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

给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。

滑动窗口 + 哈希表

整理题意:是否存在长度不超过的 k+1 窗口,窗口内有相同元素。

我们可以从前往后遍历 nums,同时使用 Set 记录遍历当前滑窗内出现过的元素。

假设当前遍历的元素为 nums[i]:

复制代码
下标小于等于 k(起始滑窗长度还不足 k+1):直接往滑窗加数,即将当前元素加入 Set 中;
下标大于 k:将上一滑窗的左端点元素 nums[i−k−1] 移除,判断当前滑窗的右端点元素 nums[i] 是否存在 Set 中,若存在,返回 True,否则将当前元素 nums[i] 加入 Set 中。

重复上述过程,若整个 nums 处理完后仍未找到,返回 False。

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

相关推荐
大聪明了25 分钟前
uniapp vue3 使用 pinia
javascript·vue.js·uni-app
_不会dp不改名_35 分钟前
leetcode_42 接雨水
算法·leetcode·职场和发展
Swaggy T35 分钟前
自动驾驶轨迹规划算法——Apollo EM Planner
人工智能·算法·自动驾驶
LilyCoder1 小时前
HTML5二十四节气网站源码
前端·javascript·html·html5
野生的编程萌新1 小时前
从冒泡到快速排序:探索经典排序算法的奥秘(二)
c语言·开发语言·数据结构·c++·算法·排序算法
iLoyalty1 小时前
防御保护15
算法·哈希算法
EF@蛐蛐堂1 小时前
【vue3】v-model 的 “新玩法“
前端·javascript·vue.js
weixin_307779131 小时前
VS Code配置MinGW64编译backward库
开发语言·c++·vscode·算法
花开富贵ii3 小时前
代码随想录算法训练营四十三天|图论part01
java·数据结构·算法·深度优先·图论
weixin_307779133 小时前
AWS Lambda解压缩S3 ZIP文件流程
python·算法·云计算·aws