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 numsi == numsj 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 ,满足 numsi == numsj 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。

滑动窗口 + 哈希表

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

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

假设当前遍历的元素为 numsi

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

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

class Solution:

def containsNearbyDuplicate(self, nums: Listint, k: int) -> bool:

n = len(nums)

s = set()

for i in range(n):

if i > k:

s.remove(numsi - k - 1)

if numsi in s:

return True

s.add(numsi)

return False

相关推荐
kyriewen1 天前
我手写了一个 EventEmitter,面试官追问了 6 个问题——第 4 个我没答上来
前端·javascript·面试
山河木马1 天前
矩阵专题2-怎么创建视图矩阵(uViewMatrix)
javascript·webgl·计算机图形学
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
tangdou3690986551 天前
AI真好玩系列-2分钟快速了解DeepAgents | Quick Guide to DeepAgents in 2 Minutes
前端·javascript·后端
张元清1 天前
React useIntersectionObserver Hook:懒加载与可见性检测(2026)
javascript·react.js
彭于晏爱编程1 天前
纯 JS + Node,一个下午手搓了能读懂公司代码的 AI 助手,老板以为我转行了
前端·javascript
妙码生花1 天前
从 PHP 到 AI + Golang,程序员自救转型手记(十四):眨眼小人登录页制作
前端·javascript·ai编程
妙码生花1 天前
从 PHP 到 AI + Golang,程序员自救转型手记(十三):前端路由初始化
前端·javascript·ai编程
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法