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

Constraints:

1 <= nums.length <= 105

-109 <= nums[i] <= 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;
    }
};
相关推荐
jf加菲猫2 分钟前
第2章 Hello World
开发语言·c++·qt·ui
Doro再努力11 分钟前
2025_11_14洛谷【入门1】数据结构刷题小结
前端·数据结构·算法
yolo_guo19 分钟前
opencv 学习: QA_01 什么是图像锐化
linux·c++·opencv·计算机视觉
蒙奇D索大20 分钟前
【算法】回溯算法精讲:从深度优先搜索到剪枝优化
经验分享·笔记·算法·深度优先·剪枝·改行学it
QTreeY12320 分钟前
yolov5/8/9/10/11/12/13+deep-oc-sort算法的目标跟踪实现
人工智能·算法·yolo·目标检测·计算机视觉·目标跟踪
_OP_CHEN24 分钟前
算法基础篇:(六)基础算法之双指针 —— 从暴力到高效的优化艺术
c++·算法·acm·优化算法·双指针·oj题·算法蓝桥杯
cs麦子26 分钟前
C语言--详解--指针--下
c语言·数据结构·算法
flashlight_hi32 分钟前
LeetCode 分类刷题:3217. 从链表中移除在数组中存在的节点
javascript·数据结构·leetcode·链表
Tisfy1 小时前
LeetCode 2536.子矩阵元素加 1:二维差分数组
算法·leetcode·矩阵
北邮刘老师1 小时前
智能家居,需要的是“主控智能体”而不是“主控节点”
人工智能·算法·机器学习·智能体·智能体互联网