Skip to content

Commit 90cd29e

Browse files
committed
solve 217 with O(n)
1 parent 66bf29d commit 90cd29e

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
* Author: illuz <iilluzen[at]gmail.com>
3+
* File: AC_bucket_n.java
4+
* Create Date: 2015-07-16 10:57:54
5+
* Descripton: Description see https://leetcode.com/discuss/38206/ac-o-n-solution-in-java-using-buckets-with-explanation
6+
*/
7+
8+
public class Solution {
9+
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
10+
if (k < 1 || t < 0) return false;
11+
Map<Long, Long> map = new HashMap<>();
12+
for (int i = 0; i < nums.length; i++) {
13+
long remappedNum = (long) nums[i] - Integer.MIN_VALUE;
14+
long bucket = remappedNum / ((long) t + 1);
15+
if (map.containsKey(bucket)
16+
|| (map.containsKey(bucket - 1) && remappedNum - map.get(bucket - 1) <= t)
17+
|| (map.containsKey(bucket + 1) && map.get(bucket + 1) - remappedNum <= t))
18+
return true;
19+
if (map.entrySet().size() >= k) {
20+
long lastBucket = ((long) nums[i - k] - Integer.MIN_VALUE) / ((long) t + 1);
21+
map.remove(lastBucket);
22+
}
23+
map.put(bucket, remappedNum);
24+
}
25+
return false;
26+
}
27+
}
28+

0 commit comments

Comments
 (0)