当前位置:网站首页>力扣(LeetCode)219. 存在重复元素 II(2022.08.07)
力扣(LeetCode)219. 存在重复元素 II(2022.08.07)
2022-08-08 10:51:00 【ChaoYue_miku】
给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。
示例 1:
输入:nums = [1,2,3,1], k = 3
输出:true
示例 2:
输入:nums = [1,0,1,1], k = 1
输出:true
示例 3:
输入:nums = [1,2,3,1,2,3], k = 2
输出:false
提示:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
0 <= k <= 105
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/contains-duplicate-ii
方法一:滑动窗口
C++提交内容:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_set<int> s;
int length = nums.size();
for (int i = 0; i < length; i++) {
if (i > k) {
s.erase(nums[i - k - 1]);
}
if (s.count(nums[i])) {
return true;
}
s.emplace(nums[i]);
}
return false;
}
};
边栏推荐
猜你喜欢
随机推荐
Apple developer account application process full version
目标检测中的Classificition Loss
2022 world conference on robots is holding, intelligent robot booster to intelligent, digital transformation and upgrading traditional industry
便利贴--48{再次,适配屏幕宽高class}
键值数据库是将什么作为标识符的呢?
dedecms支持Word图文一键导入
Timed Task Framework Quartz-(1) Quartz Introduction and Demo Construction
《STM32MP1 M4裸机CubeIDE开发指南》第二十四章 DAC实验
模式识别 学习笔记:第七章 特征选择
Alibaba微服务组件Nacos注册中心
使用文档数据库的目的是什么呢?
How to uniformly handle error exceptions in embedded C programming?
关于win下面Celery服务报 Process 'Worker' exited with 'exitcode 1' [duplicate]
部署spark2.2集群(standalone模式)
一文读懂配置管理(CM)
Optional常用方法解析
TCP通信
LeetCode_14_最长公共前缀
四、哈希表
Dubins curve study notes and related thinking