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;
    }
};
相关推荐
天选之女wow6 分钟前
【Hard——Day8】65.有效数字、68.文本左右对齐、76.最小覆盖子串
linux·运维·redis·算法·leetcode
AI大模型学徒15 分钟前
NLP基础(八)_马尔可夫模型
算法·机器学习·自然语言处理·nlp·概率论·马尔可夫模型
前端小L35 分钟前
图论专题(十八):“逆向”拓扑排序——寻找图中的「最终安全状态」
数据结构·算法·安全·深度优先·图论·宽度优先
前端小L37 分钟前
图论专题(十七):从“判定”到“构造”——生成一份完美的「课程表 II」
算法·矩阵·深度优先·图论·宽度优先
qq_433554541 小时前
C++ 稀疏表
开发语言·c++·算法
Bona Sun1 小时前
单片机手搓掌上游戏机(十二)—esp8266运行gameboy模拟器之编译上传
c语言·c++·单片机·游戏机
帅中的小灰灰1 小时前
C++编程观察者设计模式
数据库·c++·设计模式
2501_941800881 小时前
5G技术引领下的智能制造革命:如何推动工业4.0发展
leetcode
小白程序员成长日记2 小时前
2025.11.21 力扣每日一题
算法·leetcode·职场和发展
MSTcheng.2 小时前
【C++STL】priority_queue 模拟实现与仿函数实战
开发语言·c++