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;
    }
};
相关推荐
夏日听雨眠19 小时前
数据结构(循环队列)
数据结构·算法·链表
Languorous.19 小时前
C++智能指针详解:原理、使用及避坑指南
开发语言·c++
lingzhilab19 小时前
零知派ESP32-DFPlayer MP3智能音乐播放器2
c++·mfc
平行侠19 小时前
30MacLaren-Marsaglia算法故事文件
数据结构·算法
灵动小溪20 小时前
claude code工具PC安装部署
人工智能·算法
fan_music20 小时前
C语言如何实现C++的类
开发语言·c++
Asa1213820 小时前
Nature Microbiology|跨微生物界菌株水平传播推断的新算法TRACS
算法
_君莫笑20 小时前
Qt+Qml前后端分离上位机软件技术方案
c++·qt·用户界面·qml
叼烟扛炮21 小时前
C++ 知识点22 函数模板
开发语言·c++·算法·函数模版
Tisfy21 小时前
LeetCode 2553.分割数组中数字的数位:模拟(maybe+翻转)——java也O(1)
java·数学·算法·leetcode·题解·模拟·取模