Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
暴力是个好方法。But 我们遇到问题就使用暴力,会导时间复杂度很高。本体使用暴力很容易解决,具体代码如下:
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
//思路:使用暴力方法
//双层遍历,第一层使用控制k,使K逐渐减少。第二层遍历数组,用i和j对应的数据相减与t比较
while (k > 0) {
for (int i = 0; i < nums.length; i++) {
if ((i + k) < nums.length){
if ((nums[i+k] - nums[i]) <= t){
return true;
}
}
}
k --;
}
return false;
}
上面算法的时间复杂度是O(n^2),努力的人怎么能止步于此呢?下面还有一个算法可以在O(n)的时间复杂度之内实现。
思路介绍:
假设我们的输入是:
nums = [1, 5, 17, 6, 8], t = 2, k = 5
我们根据 t 来划分窗口,每个窗口的大小是 t + 1 。创建一个窗口数组windows,我们使用windows[ 0 ] 来储存[0, 1, 2],windows[ 1 ] 来储存[3, 4, 5],以此类推。这样储存可以保证同一个窗口内的数据最大差异小于 t 。3 - 2 = 1,3 在窗口 1 中,2 在窗口 0 中,因此相邻的窗口有可能出现符合条件的值。但是6 - 2 = 4,相间隔的窗口不可能出现符合条件的值。因此接下来我们把每个数字压入窗口。
1 / 3 = 0 将 2 压入窗口 0,并与相邻的窗口 1 进行比较。窗口 1 没有值,我们继续;
5 / 3 = 1 将 5 压入窗口 1,并与相邻的窗口 0 和窗口 2 进行比较。5 - 1 = 4 > 2并且窗口 2 没有值,我们继续;
17 / 3 = 5 将 17 压入窗口 5,并与相邻的窗口 4 和窗口 6 进行比较。窗口 4 和窗口 6 没有值,我们继续;
6 / 3 = 2 将 6 压入窗口 2,并与相邻的窗口 1 和窗口 3 进行比较。6 - 5 = 1 符合条件,结束;
这里还有一个结束条件,就是两个数字同时进入同一个窗口(我们设计的时候就使同一个窗口内最大差异小于等于 t ),这也是触发结束的条件。
如果我们添加了k个数字之后,要删除最先加入的那个。因为规定好了要在 k 个数内找符合条件的值。
具体代码:
if (nums == null || k < 0 || t < 0){
return false;
}
int key, value;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
key = nums[i] / (t + 1);
value = nums[i];
if (map.containsKey(key)){
return true;
}else {
map.put(key, value);
if(map.get(key - 1) != null && Math.abs(nums[i] - map.get(key - 1)) <= t) return true;
if(map.get(key + 1) != null && Math.abs(nums[i] - map.get(key + 1)) <= t) return true;
if (map.size() > k){
map.remove(Math.floorDiv(nums[i - k], (long) t + 1));
}
}
}
return false;