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;
    }
};
相关推荐
SoleMotive.5 分钟前
redis实现漏桶算法--https://blog.csdn.net/m0_74908430/article/details/155076710
redis·算法·junit
-森屿安年-12 分钟前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode
北京地铁1号线19 分钟前
数据结构:堆
java·数据结构·算法
得物技术28 分钟前
从数字到版面:得物数据产品里数字格式化的那些事
前端·数据结构·数据分析
散峰而望38 分钟前
C++数组(一)(算法竞赛)
c语言·开发语言·c++·算法·github
自然常数e1 小时前
深入理解指针(1)
c语言·算法·visual studio
WWZZ20251 小时前
快速上手大模型:深度学习13(文本预处理、语言模型、RNN、GRU、LSTM、seq2seq)
人工智能·深度学习·算法·语言模型·自然语言处理·大模型·具身智能
Christo32 小时前
AAAI-2024《Multi-Class Support Vector Machine with Maximizing Minimum Margin》
人工智能·算法·机器学习·支持向量机·数据挖掘
元亓亓亓3 小时前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展