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 分钟前
手写一个异步日志库:从printf到高性能无锁日志
java·c语言·开发语言·c++·visual studio
2401_868534784 分钟前
2026年5月系统分析
数据结构·python·tornado
hetao17338375 分钟前
2026-05-28~06-02 hetao1733837 的刷题记录
c++·算法
ZhengEnCi5 分钟前
O08-单写线程与单读线程冲突分析
算法
wunaiqiezixin20 分钟前
如何在C++中实现一个单例模式?
c++·单例模式
仍然.21 分钟前
算法题目---优先级队列
算法
一个爱编程的人24 分钟前
图的相关概念
c++·算法·图论
迈巴赫车主25 分钟前
贪心算法
算法·贪心算法
星马梦缘38 分钟前
死锁与进程资源分配问题的解法
算法·操作系统·深度优先·死锁
爱炼丹的James43 分钟前
第四章 数学知识
算法