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;
    }
};
相关推荐
CQ_07122 小时前
自学记录:力扣hot100第三题
算法·leetcode
三体世界5 小时前
HTTPS加密原理
linux·开发语言·网络·c++·网络协议·http·https
杜子不疼.5 小时前
结构体的嵌套问题
c语言·c++
Wilber的技术分享5 小时前
【机器学习实战笔记 12】集成学习:AdaBoost算法
人工智能·笔记·算法·决策树·机器学习·分类·集成学习
mu_xing_5 小时前
opencv依据图像类型读取图像像素点
c++·opencv
小怡同学..6 小时前
c++系列之智能指针的使用
开发语言·c++
金融小师妹6 小时前
基于LSTM-GARCH混合模型的“获利了结”量化解析:黄金单日1.27%跌幅的技术性归因
大数据·人工智能·算法
不良手残7 小时前
Java实现10大经典排序算法
数据结构·算法·排序算法
是紫焅呢7 小时前
I排序算法.go
开发语言·后端·算法·golang·排序算法·学习方法·visual studio code
mxpan8 小时前
C++ 单例模式一种实现方式
c++·设计模式