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;
    }
};
相关推荐
云qq几秒前
C++ 原子操作
开发语言·c++·算法
A charmer4 分钟前
第一章:基础语法破冰|从 C++ 无缝切换 OC 语法
c++·objective-c
xrgs_shz9 分钟前
基于轻量化浅层卷积神经网络的手写数字识别
算法·matlab·cnn
许彰午12 分钟前
02-手写链表、栈、队列——不依赖任何集合框架
数据结构·链表·面试
MegaDataFlowers13 分钟前
141.环形链表
数据结构·链表
fffzd13 分钟前
C++入门(一)
开发语言·c++·命名空间·输入输出·缺省参数
计算机安禾20 分钟前
【计算机网络】第10篇:距离矢量路由算法——Bellman-Ford方程与RIP协议的特性分析
计算机网络·算法
机器学习之心28 分钟前
基于开普勒优化算法(KOA)优化CNN-BiGRU-Attention混合网络的时间序列预测模型,MATLAB代码
算法·时间序列预测模型·开普勒优化算法
草莓熊Lotso32 分钟前
Python 入门必吃透:函数、列表与元组核心用法(附实战案例)
大数据·服务器·开发语言·c++·人工智能·python·qt
Java成神之路-1 小时前
【LeetCode 刷题笔记】367.有效的完全平方数 | 二分查找经典刷题题解
算法·leetcode