-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainsDuplicateTwo.java
More file actions
25 lines (23 loc) · 677 Bytes
/
ContainsDuplicateTwo.java
File metadata and controls
25 lines (23 loc) · 677 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package leetcode.array;
import java.util.HashSet;
/**
* @ClassName ContainsDuplicateTwo
* @Description 存在重复元素2 https://leetcode-cn.com/problems/contains-duplicate-ii/
* @Author changxuan
* @Date 2020/11/5 下午10:12
**/
public class ContainsDuplicateTwo {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashSet<Integer> con = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (con.contains(nums[i])) {
return true;
}
con.add(nums[i]);
if (con.size() > k) {
con.remove(nums[i-k]);
}
}
return false;
}
}