forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainsDuplicateIII.java
More file actions
23 lines (21 loc) · 827 Bytes
/
ContainsDuplicateIII.java
File metadata and controls
23 lines (21 loc) · 827 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class ContainsDuplicateIII.java {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Long> set = new TreeSet<>();
for(int i=0;i<nums.length;i++){ // O(n)
Long el = new Long(nums[i]);
Long floor = set.floor(el); //next lower value O(log k) in treeset
Long ceil = set.ceiling(el); // next higher value O(log k) in treeset
if(floor!=null && Math.abs(floor-el)<=t){
return true;
}
if(ceil!=null && Math.abs(ceil-el)<=t){
return true;
}
set.add(el);
if(set.size()>k){ // size of set is always k and hence becomes a sliding window problem
set.remove(new Long(nums[i-k]));
}
}
return false;
}
}