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

Constraints:

1 <= nums.length <= 105

-109 <= numsi <= 109

0 <= k <= 105

二、题解

cpp 复制代码
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int n = nums.size();
        unordered_map<int,int> map;
        for(int i = 0;i < n;i++){
            if(map.find(nums[i]) == map.end()) map[nums[i]] = i;
            else{
                if(abs(map[nums[i]] - i) <= k) return true;
                map[nums[i]] = i;
            }
        }
        return false;
    }
};
相关推荐
小poop3 分钟前
轮转数组:从暴力到最优,一题掌握算法复杂度分析
数据结构·算法·leetcode
樱桃读报僵尸26 分钟前
说说 LLMRouter,Agent 执行过程中怎么动态的选择 LLM
算法
汉克老师43 分钟前
GESP2026年3月认证C++八级( 第三部分编程题(2、子图最短路)精讲
c++·最短路·floyd·gesp8级
gis开发之家1 小时前
《Vue3 从入门到大神40篇》Vue3 源码详解(十):diff 算法全解析 —— 为什么 Vue3 比 Vue2 更快?
javascript·算法·typescript·前端框架·vue3·vue3源码
进击的丸子1 小时前
虹软人脸服务器SDK-C++语言Demo实操指南
后端·算法
abcd_zjq2 小时前
海康线扫相机使用
c++·海康
十五年专注C++开发2 小时前
C++设计一个函数来求容器元素绝对值之和的平均值
c++·模板·accumulate
SilentSlot2 小时前
【C/C++】手写 DPDK 协议栈(十一):基于 PPS、SYN 比例和源 IP 熵的 DDoS 检测
c语言·c++·tcp/ip
兰令水2 小时前
hot100【acm版】【2026.7.25/26打卡-java版本】
java·算法·排序算法
音视频工程实战2 小时前
PromptQL 新手入门与实战指南
数据库·sql·算法