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;
    }
};
相关推荐
不知名的老吴几秒前
C++ 中函数对象的形式概述
开发语言·c++
搬砖者(视觉算法工程师)2 分钟前
计算机视觉与计算摄影测量学第三讲图像直方图:理论、统计特性与点运算变换
人工智能·算法·计算机视觉
Yingjun Mo7 分钟前
3. Meta-Harness:模型基座外壳的端到端优化
人工智能·算法
Cthy_hy9 分钟前
并查集(Disjoint Set Union):巧判「连通聚类关系」的极简利器
数据结构·算法
Shan120510 分钟前
C++中函数对象之重载 operator()
开发语言·c++·算法
逻辑君10 分钟前
物理生物学研究报告【20260007】
人工智能·算法
阿维的博客日记15 分钟前
简单说一下ArrayList的add机制,适合应试者表达的
算法·arraylist
djarmy35 分钟前
一级函数头地址指针,(*p_func)的函数头的返回值,(*p_func)的函数头的参数列表
c++
阿Y加油吧36 分钟前
两道位运算 / 摩尔投票经典题复盘:只出现一次的数字 & 多数元素
数据结构·算法·leetcode
小明同学0138 分钟前
C++后端项目:统一大模型接入 SDK(一)
linux·c++·chatgpt