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;
    }
};
相关推荐
自我意识的多元宇宙3 小时前
树与二叉树--二叉树的存储结构
数据结构
BestOrNothing_20154 小时前
C++零基础到工程实战(4.3.3):vector数组访问与遍历
c++·迭代器·stl·vector·动态数组
charlie1145141914 小时前
通用GUI编程技术——图形渲染实战(三十三)——Direct2D与Win32/GDI互操作:渐进迁移实战
c++·图形渲染·gui·win32
文祐4 小时前
C++类之虚函数表及其内存布局(一个子类继承一个父类)
开发语言·c++
白羊by4 小时前
YOLOv1~v11 全版本核心演进总览
深度学习·算法·yolo
墨尘笔尖6 小时前
最大最小值降采样算法的优化
c++·算法
自我意识的多元宇宙7 小时前
二叉树的遍历和线索二叉树--二叉树的遍历
数据结构
YIN_尹8 小时前
【Linux系统编程】进程地址空间
linux·c++
qq_5024289908 小时前
清华大学与微软亚洲研究院出品:Kronos 本地部署教程
数据结构·python·金融量化·kronos开源模型
EverestVIP8 小时前
C++中空类通常大小为1的原理
c++