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;
    }
};
相关推荐
长安er4 小时前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
元亓亓亓4 小时前
LeetCode热题100--62. 不同路径--中等
算法·leetcode·职场和发展
小白菜又菜4 小时前
Leetcode 1925. Count Square Sum Triples
算法·leetcode
粉红色回忆4 小时前
用链表实现了简单版本的malloc/free函数
数据结构·c++
登山人在路上5 小时前
Nginx三种会话保持算法对比
算法·哈希算法·散列表
写代码的小球5 小时前
C++计算器(学生版)
c++·算法
AI科技星5 小时前
张祥前统一场论宇宙大统一方程的求导验证
服务器·人工智能·科技·线性代数·算法·生活
k***92166 小时前
【C++】继承和多态扩展学习
java·c++·学习
予枫的编程笔记6 小时前
Redis 核心数据结构深度解密:从基础命令到源码架构
java·数据结构·数据库·redis·缓存·架构
wadesir6 小时前
掌握Rust并发数据结构(从零开始构建线程安全的多线程应用)
数据结构·安全·rust