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
给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ。
示例 1:
输入: nums = [1,2,3,1], k = 3, t = 0 输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1, t = 2 输出: true
示例 3:
输入: nums = [1,5,9,1,5,9], k = 2, t = 3 输出: false
题解:这题是之前的Contains Duplicate和Contains Duplicate II这两题的升级版,此题又增加了关于nums [i]和nums [j]这两个元素的差的绝对值要在某一个区间内,而不是说如Contains Duplicate II这题,两个元素是相等的那样。如果采用普通的双层for循环,那么必然超时,而且此题需要考虑nums [i]和nums [i]这两个元素刚好处于int类型的边界,那么两者相减所得到的值会超过普通int类型的界,会出现越界的问题。那么就引入一个TreeSet的数据结构,用于存储当前数组元素的绝对值为k的元素,每次碰到一个新的数组元素,对比这个元素是否在保存的set的子集中,如果在set的子集中,那么就直接返回true;否则继续添加当前元素入set中,而且需要比较当前的值是否超过k值,如果大于,那么就压入set中,否则就压出。
public static boolean containsNearbyAlmostDuplicate(int[] nums,int k,int t)
{
if(k < 1 || t < 0 || nums == null || nums.length < 2)
return false;
SortedSet<Long> set = new TreeSet<>();
for(int i = 0; i < nums.length; i++)
{
SortedSet<Long> subset = set.subSet((long)nums[i] - t,(long)nums[i]+t+1);
if(!subset.isEmpty())
return true;
if(i >= k)
set.remove((long)nums[i-k]);
set.add((long)nums[i]);
}
return false;
}