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;
    }
};
相关推荐
想放学的刺客5 小时前
整理了120道单片机嵌入式面试题与答案,覆盖了硬件电路和C语言等核心领域。
c语言·c++·stm32·单片机·嵌入式硬件·mcu·51单片机
舟舟亢亢6 小时前
算法总结——二叉树【hot100】(上)
java·开发语言·算法
weixin_477271697 小时前
根象:树根。基石。基于马王堆帛书《周易》原文及甲骨文还原周朝生活活动现象(《函谷门》原创)
算法·图搜索算法
普通网友7 小时前
多协议网络库设计
开发语言·c++·算法
努力努力再努力wz7 小时前
【Linux网络系列】:TCP 的秩序与策略:揭秘传输层如何从不可靠的网络中构建绝对可靠的通信信道
java·linux·开发语言·数据结构·c++·python·算法
汉克老师7 小时前
GESP2024年3月认证C++二级( 第二部分判断题(1-10))
c++·循环结构·分支结构·gesp二级·gesp2级
daxi1507 小时前
C语言从入门到进阶——第9讲:函数递归
c语言·开发语言·c++·算法·蓝桥杯
持续学习的程序员+18 小时前
强化学习Q-chunking算法
算法
Polaris北8 小时前
第二十七天打卡
开发语言·c++·算法
风吹乱了我的头发~9 小时前
Day30:2026年2月20日打卡
算法