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;
    }
};
相关推荐
生成论实验室3 分钟前
机器人:一个自主运动的系统
人工智能·算法·语言模型·机器人·自动驾驶·agi·安全架构
Qres8214 分钟前
算法复键——树状数组
数据结构·算法
H178535090964 分钟前
SolidWorks第四部分_直接实体建模特征9_替换面原理
线性代数·算法·机器学习·3d建模·solidworks
凡人叶枫14 分钟前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
不会就选b17 分钟前
算法日常・每日刷题--<二分查找>3
算法
凡人叶枫19 分钟前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss28 分钟前
BRpc使用
c++·rpc
绿算技术1 小时前
Mooncake 与绿算ForinnBase GroundPool如何联手打破推理僵局?
科技·算法·架构
-森屿安年-1 小时前
63. 不同路径 II
c++·算法·动态规划
chase_my_dream1 小时前
Cartographer详细讲解
c++·人工智能·自动驾驶