-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathContainsDuplicates3.java
38 lines (37 loc) · 1.43 KB
/
ContainsDuplicates3.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
/*https://leetcode.com/problems/contains-duplicate-iii/*/
class Solution {
public boolean containsNearbyAlmostDuplicate(int[] arr, int k, int t) {
long[] nums = new long[arr.length];
for (int i = 0; i < nums.length; ++i)
nums[i] = (long)arr[i];
TreeMap<Long,Integer> map = new TreeMap<Long,Integer>();
Long low, high;
if (k >= nums.length)
{
for (int i = 0; i < nums.length; ++i)
{
low = map.lowerKey(nums[i]);
high = map.higherKey(nums[i]);
if ((low != null && low >= nums[i]-t) || (high != null && high <= nums[i]+t) || map.containsKey(nums[i])) return true;
map.put(nums[i],1);
}
return false;
}
for (int i = 0; i <= k; ++i)
{
low = map.lowerKey(nums[i]);
high = map.higherKey(nums[i]);
if ((low != null && low >= nums[i]-t) || (high != null && high <= nums[i]+t) || map.containsKey(nums[i])) return true;
map.put(nums[i],1);
}
for (int i = k+1; i < nums.length; ++i)
{
map.remove(nums[i-k-1]);
low = map.lowerKey(nums[i]);
high = map.higherKey(nums[i]);
if ((low != null && low >= nums[i]-t) || (high != null && high <= nums[i]+t) || map.containsKey(nums[i])) return true;
map.put(nums[i],1);
}
return false;
}
}