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;
    }
};
相关推荐
Gomiko11 分钟前
C/C++基础(四):运算符
c语言·c++
苏小瀚15 分钟前
[算法]---路径问题
数据结构·算法·leetcode
freedom_1024_22 分钟前
【c++】使用友元函数重载运算符
开发语言·c++
zmzb010344 分钟前
C++课后习题训练记录Day43
开发语言·c++
月明长歌1 小时前
【码道初阶】一道经典简单题:多数元素(LeetCode 169)|Boyer-Moore 投票算法详解
算法·leetcode·职场和发展
wadesir1 小时前
C语言模块化设计入门指南(从零开始构建清晰可维护的C程序)
c语言·开发语言·算法
t198751281 小时前
MATLAB水声信道仿真程序
开发语言·算法·matlab
赖small强1 小时前
【Linux C/C++开发】 GCC -g 调试参数深度解析与最佳实践
linux·c语言·c++·gdb·-g
前端之虎陈随易1 小时前
MoonBit内置数据结构详解
数据结构·数据库·redis
CAE虚拟与现实2 小时前
C/C++中“静态链接(Static Linking)” 和 “动态链接(Dynamic Linking)释疑
开发语言·c++·dll·动态链接库·lib库