(220)-(Contains Duplicate III)-(判断数组中是否位置差至多为k时,值差最多为t)-(特殊解法,用treeset中的floor和ceiling)
(220)-(Contains Duplicate III)-(判断数组中是否位置差至多为k时,值差最多为t)-(特殊解法,用treeset中的floor和ceiling) //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. lower 返回小于 给定元素的元素 floor 返回小于等于 给定元素的元素 ceiling 返回大于等于 给定元素的元素 higher 返回大于 给定元素的元素 如果不存在这样的元素,则返回 null public class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { //位置差或值差不合理 if(k < 1 || t < 0) { return false; } int cap=k+1; TreeSet<Integer> set = new TreeSet<>(); for(int i = 0; i < nums.length; i++) { if(i<cap) { //不进行操作 } else { set.remove(nums[i - cap]); } int n = nums[i]; //存在(小于等于n)的元素且(小于等于n)的元素都(大于等于n-t) //或者 //存在(大于等于n)的元素且(大于等于n)的元素都(小于等于n+t) if(set.floor(n) != null && set.floor(n) >= n - t || set.ceiling(n) != null && set.ceiling(n) <= t + n) { return true; } else { set.add(n); } } return false; } }