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 numsi == numsj 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 <= numsi <= 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;
    }
};
相关推荐
一木 之林6 小时前
五、C++新特性、关键字与编译原理
java·jvm·算法
汉克老师6 小时前
CSP-J 初赛(以满分为目标):第四课《看懂计算机到底在算什么!——C++变量、表达式和运算符 》
c++·小学生·学c++编程
小小龙学IT6 小时前
zstd(Zstandard)开源压缩库实战指南:让数据又快又小
c++·开源
圣保罗的大教堂7 小时前
leetcode 3718. 缺失的最小倍数 简单
leetcode
小小龙学IT7 小时前
GLM 开源图形学数学库深度解析:从向量、矩阵到四元数的完整实战
c++·矩阵·开源·mfc
dtq04247 小时前
数据结构 - 线性表 - 单链表
数据结构
Severus_black7 小时前
【C++初阶】类和对象(中)
c++
万法若空7 小时前
对数恒等式
人工智能·算法·机器学习
青 春 记 忆7 小时前
LeetCode 234. 回文链表|Python 解法详解
python·leetcode·链表
AI小码8 小时前
如何让AI帮你构建项目?七级方法
人工智能·算法·计算机·ai·程序员·大模型·编程