Given an array of integers, find out whether there is II distinct indices i and J in the array such th At the difference between nums[i] and Nums[j] are at most T and the difference between I and J I S at the most K.
Thought for reference: maintain a window of length k, each time checking whether the new value is less than or equal to the value of all values in the original window. If the two for loop will time out O (NK). You can quickly search by using the subset function of TreeSet (backed by binary search tree). Complexity of O (n logk)
The code is as follows:
Import Java.util.sortedset;public class Solution {public 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<> (); int len=nums.length; for (int i=0;i<len;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; }}
Operation Result:
(Medium) Leetcode 220.Contains Duplicate III