leetcode-master/problems/0219.存在重复元素II.md

52 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 题目地址
https://leetcode-cn.com/problems/contains-duplicate-ii/
## 思路
使用哈希策略map数据结构来记录数组元素和对应的元素所在下表看代码已经详细注释。
## C++代码
```
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> map; // key: 数组元素, value元素所在下表
for (int i = 0; i < nums.size(); i++) {
// 找到了在索引i之前就出现过nums[i]这个元素
if (map.find(nums[i]) != map.end()) {
int distance = i - map[nums[i]];
if (distance <= k) {
return true;
}
map[nums[i]] = i; // 更新元素nums[i]所在的最新位置i
} else { // 如果map里面没有就把插入一条数据<元素,元素所在的下表>
map[nums[i]] = i;
}
}
return false;
}
};
```
代码精简之后
```
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); i++) {
if (map.find(nums[i]) != map.end() && i - map[nums[i]] <= k) return true;
map[nums[i]] = i;
}
return false;
}
};
```
> 更过算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。