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;
    }
};
相关推荐
顺顺 尼2 分钟前
模板进阶和array
c++
MicroTech202510 分钟前
MLGO微算法科技发布多用户协同推理批处理优化系统,重构AI推理服务效率与能耗新标准
人工智能·科技·算法
一匹电信狗20 分钟前
【牛客CM11】链表分割
c语言·开发语言·数据结构·c++·算法·leetcode·stl
困鲲鲲22 分钟前
ROS2系列 (10) : C++话题通信节点——发布者示例
c++·ros2
..过云雨22 分钟前
11.【Linux系统编程】文件系统详解——从磁盘硬件到文件系统
linux·c++·后端·缓存
不染尘.26 分钟前
图的邻接矩阵实现以及遍历
开发语言·数据结构·vscode·算法·深度优先
xiaoye-duck26 分钟前
数据结构之栈和队列-栈
数据结构
码住懒羊羊35 分钟前
【C++】模板进阶 | 继承
android·java·c++
山峰哥37 分钟前
KingbaseES 表空间与模式优化策略深度研究报告
开发语言·数据结构·数据库·oracle·深度优先
AndrewHZ40 分钟前
【图像处理基石】多波段图像融合算法入门:从概念到实践
图像处理·人工智能·算法·图像融合·遥感图像·多波段·变换域