algorithm-base/animation-simulation/数组篇/leetcode219数组中重复元素2.md

94 lines
3.4 KiB
Java
Raw Normal View History

2021-03-20 08:30:29 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 07:48:03 +00:00
### [219 2](https://leetcode-cn.com/problems/contains-duplicate-ii/)
2021-03-17 11:49:19 +00:00
****
k i j使 nums [i] = nums [j] i j k
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
**Hashmap**
K HashMap
```java
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
//特殊情况
if (nums.length == 0) {
return false;
}
// hashmap
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
// 如果含有
if (map.containsKey(nums[i])) {
//判断是否小于K如果小于则直接返回
int abs = Math.abs(i - map.get(nums[i]));
if (abs <= k) return true;//小于则返回
}
//更新索引,此时有两种情况,不存在,或者存在时,将后出现的索引保存
map.put(nums[i],i);
}
return false;
}
}
```
**HashSet**
****
K true
![leetcode2192](https://cdn.jsdelivr.net/gh/tan45du/test1@master/20210122/leetcode219数组中重复元素2.6m947ehfpb40.gif)
****
```java
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
//特殊情况
if (nums.length == 0) {
return false;
}
// set
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; ++i) {
//含有该元素返回true
if (set.contains(nums[i])) {
return true;
}
// 添加新元素
set.add(nums[i]);
//维护窗口长度
if (set.size() > k) {
set.remove(nums[i-k]);
}
}
return false;
}
}
```