4
4
5
5
/**
6
6
* 220. Contains Duplicate III
7
- * <p>
7
+ *
8
8
* Given an array of integers, find out whether there are two
9
9
* distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at
10
10
* most t and the difference between i and j is at most k.
@@ -22,15 +22,13 @@ public static class Solution1 {
22
22
/**
23
23
* TreeSet turns out to be a super handy data structure for this problem. It implements Set
24
24
* interface and keeps elements in sorted order, plus it has two very handy APIs:
25
- * <p>
26
25
* https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#ceiling(E): Returns the
27
26
* least element in this set greater than or equal to the given element, or null if there is no
28
27
* such element.
29
- * <p>
30
28
* https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#floor(E): Returns the
31
29
* greatest element in this set less than or equal to the given element, or null if there is no
32
30
* such element.
33
- * <p>
31
+ *
34
32
* Idea: loop through this array, keep adding each element into the TreeSet, also keep an eye on
35
33
* the size of the TreeSet, if it's greater than the required distance of k, then we remove the
36
34
* left-most or oldest one from the set. For each element, we get the current floor and the
@@ -39,23 +37,22 @@ public static class Solution1 {
39
37
*/
40
38
41
39
public boolean containsNearbyAlmostDuplicate (int [] nums , int k , int t ) {
42
- TreeSet <Integer > set = new TreeSet <>();
40
+ /**case to Long to avoid Integer overflow.*/
41
+ TreeSet <Long > set = new TreeSet <>();
43
42
for (int i = 0 ; i < nums .length ; ++i ) {
44
- // Find the successor of current element
45
- Integer s = set .ceiling (nums [i ]);
46
- if (s != null && s <= nums [i ] + t ) {
43
+ Long s = set .ceiling ((long ) nums [i ]);
44
+ if (s != null && s - nums [i ] <= t ) {
47
45
return true ;
48
46
}
49
47
50
- // Find the predecessor of current element
51
- Integer g = set .floor (nums [i ]);
52
- if (g != null && nums [i ] <= g + t ) {
48
+ Long g = set .floor ((long ) nums [i ]);
49
+ if (g != null && nums [i ] - g <= t ) {
53
50
return true ;
54
51
}
55
52
56
- set .add (nums [i ]);
53
+ set .add (( long ) nums [i ]);
57
54
if (set .size () > k ) {
58
- set .remove (nums [i - k ]);
55
+ set .remove (( long ) nums [i - k ]);
59
56
}
60
57
}
61
58
return false ;
0 commit comments