Description:
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.
题目大意:给定一个数组,和两个数t和k。判断是否满足下列条件的数。存在两个不同的下标i,j满足: nums[i] - nums[j] | <= t 且 | i - j | <= k。
思路:使用Java中的TreeSet,TreeSet是有序的内部是红黑树实现的。并且内部带有操作方法很方便,会降低问题的复杂度。其实就是一个滑动窗口,把可能满足条件的范围从左向右滑动,直到找出满足条件的数或者窗口滑动完毕。
实现代码:
public class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { if(k < 1 || t < 0) return false; TreeSet<Integer> set = new TreeSet<Integer>(); for(int i=0; i<nums.length; i++) { int cur = nums[i]; Integer floor = set.floor(cur); Integer ceil = set.ceiling(cur); if(floor != null && cur <= t + floor || ceil != null && ceil <= t + cur) { return true; } set.add(cur); if(i >= k) { set.remove(nums[i - k]); } } return false; } }