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;
    }
};
相关推荐
cpp_250112 分钟前
P1024 [NOIP 2001 提高组] 一元三次方程求解
数据结构·c++·算法·题解·二分答案·洛谷·csp
田梓燊7 小时前
力扣:23.合并 K 个升序链表
算法·leetcode·链表
re林檎7 小时前
算法札记——4.27
算法
AI人工智能+电脑小能手8 小时前
【大白话说Java面试题】【Java基础篇】第15题:JDK1.7中HashMap扩容为什么会发生死循环?如何解决
java·开发语言·数据结构·后端·面试·哈希算法
数据牧羊人的成长笔记8 小时前
逻辑回归与Softmax回归
算法·回归·逻辑回归
郑州光合科技余经理8 小时前
同城O2O海外版二次开发实战:从支付网关到配送算法
开发语言·前端·后端·算法·架构·uni-app·php
张健11564096489 小时前
使用信号量限制并发数量
开发语言·c++
jc062010 小时前
6.1云原生之Docker
c++·docker·云原生
Mrlxl.cn10 小时前
计算机网络——网络层
c语言·数据结构·计算机网络·考研
d111111111d11 小时前
STM32-UART封装问题解析
笔记·stm32·单片机·嵌入式硬件·学习·算法