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;
    }
};
相关推荐
信奥胡老师25 分钟前
苹果电脑(mac系统)安装vscode与配置c++环境,并可以使用万能头文件全流程
c++·ide·vscode·macos·编辑器
妖灵翎幺26 分钟前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
风筝在晴天搁浅39 分钟前
代码随想录 718.最长重复子数组
算法
kyle~43 分钟前
算法---回溯算法
算法
star _chen1 小时前
C++实现完美洗牌算法
开发语言·c++·算法
hzxxxxxxx1 小时前
1234567
算法
繁星星繁2 小时前
【C++】脚手架学习笔记 gflags与 gtest
c++·笔记·学习
Sylvia-girl2 小时前
数据结构之复杂度
数据结构·算法
CQ_YM2 小时前
数据结构之队列
c语言·数据结构·算法·
VekiSon2 小时前
数据结构与算法——树和哈希表
数据结构·算法