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;
    }
};
相关推荐
liulilittle2 小时前
FileStream C++
开发语言·c++·cocoa
Gomiko2 小时前
C/C++基础(五):分支
c语言·c++
wearegogog1232 小时前
光谱分析波段选择的连续投影算法
算法
点PY3 小时前
C++ 中 std::async 和 std::future 的并发性
java·开发语言·c++
执笔论英雄3 小时前
【RL】DAPO 数据处理
算法
不会代码的小猴3 小时前
C++的第九天笔记
开发语言·c++·笔记
why1513 小时前
面经整理——算法
java·数据结构·算法
悦悦子a啊4 小时前
将学生管理系统改造为C/S模式 - 开发过程报告
java·开发语言·算法
痕忆丶4 小时前
双线性插值缩放算法详解
算法
fqbqrr4 小时前
2512C++,clangd支持模块
开发语言·c++