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;
    }
};
相关推荐
chem411114 分钟前
C 语言 函数指针和函数指针数组
c语言·数据结构·算法
言言的底层世界34 分钟前
c++中STL容器及算法等
开发语言·c++·经验分享·笔记
Mr_WangAndy41 分钟前
C++17 新特性_第一章 C++17 语言特性___has_include,u8字符字面量
c++·c++40周年·c++17新特性·__has_include·u8字面量
liu****1 小时前
八.函数递归
c语言·开发语言·数据结构·c++·算法
客梦1 小时前
数据结构-树结构
数据结构·笔记
CM莫问1 小时前
详解机器学习经典模型(原理及应用)——岭回归
人工智能·python·算法·机器学习·回归
DuHz1 小时前
论文阅读——Edge Impulse:面向微型机器学习的MLOps平台
论文阅读·人工智能·物联网·算法·机器学习·edge·边缘计算
梦想的旅途21 小时前
基于雪花算法(Snowflake)的 Go 语言唯一 ID 生成与并发安全实现
算法·安全·golang
Vanranrr1 小时前
C++临时对象与悬空指针:一个导致资源加载失败的隐藏陷阱
服务器·c++·算法
BestOrNothing_20152 小时前
【C++基础】Day 5:struct 与 class
c++·c·class类·struct结构体·typename模板·private与public