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;
    }
};
相关推荐
怕浪猫1 小时前
RAG 面试 6 连问,从原理到优化全部覆盖
python·算法·面试
无线通信科研笔记2 小时前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
mmmmath_33 小时前
二叉树の递归遍历
算法
All for pursuit.3 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
小师兄吃牛肉4 小时前
C语言中的nullptr有必要吗
c语言·c++·算法
WL学习笔记4 小时前
日期类(C++)
开发语言·c++·日期类实现
H.莓飛5 小时前
【C++】命名空间、缺省参数、函数重载与引用
linux·开发语言·c++·visual studio
一只小小的芙厨5 小时前
【线性DP】
学习·算法·动态规划
xxwl5855 小时前
数据结构知识点和代码实现总结(C语言实现)
c语言·开发语言·数据结构
奋发向前wcx6 小时前
CSP-J复赛模拟赛5 王晨旭补题 2026.10.5
算法