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;
    }
};
相关推荐
緈福的街口5 分钟前
【leetcode】584. 寻找用户推荐人
算法·leetcode·职场和发展
future141210 分钟前
游戏开发日记
数据结构·学习·c#
今天背单词了吗98012 分钟前
算法学习笔记:17.蒙特卡洛算法 ——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·笔记·考研·算法·蒙特卡洛算法
Maybyy33 分钟前
力扣242.有效的字母异位词
java·javascript·leetcode
wjcurry41 分钟前
完全和零一背包
数据结构·算法·leetcode
逐花归海.41 分钟前
『 C++ 入门到放弃 』- 多态
开发语言·c++·笔记·程序人生
hie988941 小时前
采用最小二乘支持向量机(LSSVM)模型预测气象
算法·机器学习·支持向量机
qq_433554541 小时前
C++ 选择排序、冒泡排序、插入排序
数据结构
python_tty1 小时前
排序算法(一):冒泡排序
数据结构·算法·排序算法
卡卡_R-Python2 小时前
C++编程基础
c++