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

143 lines
4.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[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>进入。
### [219 2](https://leetcode-cn.com/problems/contains-duplicate-ii/)
****
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 Code:
```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;
}
}
```
Python3 Code:
```python
from typing import List
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int)->bool:
#
if len(nums) == 0:
return False
#
m = {}
for i in range(0, len(nums)):
#
if nums[i] in m.keys():
# K
a = abs(i - m[nums[i]])
if a <= k:
return True#
#
m[nums[i]] = i
return False
```
**HashSet**
****
K true
![leetcode2192](https://cdn.jsdelivr.net/gh/tan45du/test1@master/20210122/leetcode219数组中重复元素2.6m947ehfpb40.gif)
****
Java Code
```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;
}
}
```
Python3 Code:
```python
from typing import List
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int)->bool:
#
if len(nums) == 0:
return False
#
s = set()
for i in range(0, len(nums)):
# True
if nums[i] in s:
return True
#
s.add(nums[i])
#
if len(s) > k:
s.remove(nums[i - k])
return False
```