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;
    }
};
相关推荐
灵感__idea2 小时前
Hello 算法:“走一步看一步”的智慧
前端·javascript·算法
lwf0061644 小时前
导数学习日记
学习·算法·机器学习
头发够用的程序员5 小时前
从滑动窗口到矩阵运算:img2col算法基本原理
人工智能·算法·yolo·性能优化·矩阵·边缘计算·jetson
武帝为此5 小时前
【数据清洗缺失值处理】
python·算法·数学建模
Halo_tjn6 小时前
Java 基于字符串相关知识点
java·开发语言·算法
念越6 小时前
算法每日一题 Day08|双指针法解决三数之和
算法·力扣
万法若空6 小时前
C++ <memory> 库全方位详解
开发语言·c++
黎阳之光6 小时前
黎阳之光透明管理:视频孪生重构智慧仓储新范式
人工智能·算法·安全·重构·数字孪生
代码中介商7 小时前
C++ 类型转换深度解析:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
青小莫7 小时前
C++之string(OJ练习)
开发语言·c++·stl