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;
    }
};
相关推荐
Frostnova丶7 小时前
(15)LeetCode 189. 轮转数组
数据结构·算法·leetcode
Lumos1867 小时前
故障保护与鲁棒性(十七)
算法
阿米亚波8 小时前
【C++ STL】std::list
c++·windows·笔记·stl·list
橙色阳光五月天8 小时前
CMake 构建配置文件解析
c++·cmake·plugin
手写码匠8 小时前
从零实现大模型推理引擎:Continuous Batching 与动态调度系统深度解析
人工智能·深度学习·算法·aigc
载数而行5208 小时前
C++进阶 Linux相关的静态库,动态库,第三方库
c++
wabs6668 小时前
关于单调栈【力扣503.下一个更大元素II的思考】
算法·单调栈
c238568 小时前
下篇:伸缩魔法!进阶吃透可变滑动窗口篇
c++·算法
186******205318 小时前
RuView 新手快速上手与实战指南
算法
txzrxz8 小时前
关于二维/多维前缀和
算法