forked from liuyubobobo/Play-with-Algorithm-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
40 lines (30 loc) · 1.14 KB
/
Solution.java
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.TreeSet;
// 220. Contains Duplicate III
// https://leetcode.com/problems/contains-duplicate-iii/description/
// 时间复杂度: O(nlogk)
// 空间复杂度: O(k)
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
// 这个问题的测试数据在使用int进行加减运算时会溢出
// 所以使用long long
TreeSet<Long> record = new TreeSet<Long>();
for(int i = 0 ; i < nums.length ; i ++){
if(record.ceiling((long)nums[i] - (long)t) != null &&
record.ceiling((long)nums[i] - (long)t) <= (long)nums[i] + (long)t)
return true;
record.add((long)nums[i]);
if(record.size() == k + 1)
record.remove((long)nums[i-k]);
}
return false;
}
private static void printBool(boolean b){
System.out.println(b ? "True" : "False");
}
public static void main(String[] args) {
int[] nums = {-2147483648, -2147483647};
int k = 3;
int t = 3;
printBool((new Solution()).containsNearbyAlmostDuplicate(nums, k, t));
}
}