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;
    }
};
相关推荐
fie88892 分钟前
广义 S 变换(GST)地震信号时频谱
算法
辣机小司28 分钟前
【软件设计师】自编思维导图和学习资料分享(中级已过)
java·c++·软考·软件设计师
json{shen:"jing"}44 分钟前
1-C语言的数据类型
c语言·c++·算法
im_AMBER1 小时前
数据结构 13 图 | 哈希表 | 树
数据结构·笔记·学习·算法·散列表
LYFlied1 小时前
【算法解题模板】动态规划:从暴力递归到优雅状态转移的进阶之路
数据结构·算法·leetcode·面试·动态规划
名誉寒冰1 小时前
GDB 调试与 Core Dump(段错误)排查指南(Linux/C/C++)
linux·c语言·c++
Hcoco_me1 小时前
RTMPose_JSON相关解读
算法·数据挖掘·json·聚类
高洁012 小时前
DNN案例一步步构建深层神经网络(二)
人工智能·python·深度学习·算法·机器学习
aini_lovee2 小时前
改进遗传算法求解VRP问题时的局部搜索能力
开发语言·算法·matlab
合方圆~小文2 小时前
4G定焦球机摄像头综合介绍产品指南
数据结构·数据库·人工智能