Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
Show Tags
Show Similar Problems
Have you met this question in a real interview?
Yes
No
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (nums == null || nums.length < 2 || k == 0) {
return false;
}
TreeSet<Long> set = new TreeSet<Long>();
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
Long ceil = set.ceiling((long) n);
Long floor = set.floor((long) n);
if ((ceil != null && ceil - n <= t) || (floor != null && n - floor <= t)) {
return true;
}
set.add((long) (n));
if (i >= k) {
set.remove((long) nums[i - k]);
}
}
return false;
}
}
========
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (k < 1 || t < 0) return false;
Map<Long, Long> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
long remappedNum = (long) nums[i] - Integer.MIN_VALUE;
long bucket = remappedNum / ((long) t + 1);
if (map.containsKey(bucket)
|| (map.containsKey(bucket - 1) && remappedNum - map.get(bucket - 1) <= t)
|| (map.containsKey(bucket + 1) && map.get(bucket + 1) - remappedNum <= t))
return true;
if (map.size() >= k) {
long lastBucket = ((long) nums[i - k] - Integer.MIN_VALUE) / ((long) t + 1);
map.remove(lastBucket);
}
map.put(bucket, remappedNum);
}
return false;
}
}
没有评论:
发表评论