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,下标i和j相差<=k。
解题思路:题目没说数组有序,那就得按照无序处理,可以排序,然后从头遍历;或者用个BST之类的有序数据结构,遍历数组的时候重建一下,重建的过程中判断是否有合法的解,有就返回true,否则重建完之后返回false。
public class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { if(nums==null||nums.length==0||k<=0){ return false; } TreeSet<Integer> tree = new TreeSet<>(); for(int i=0;i<nums.length;i++){ Integer big = tree.floor(nums[i]+t);//floor返回集合里<=指定元素的最大值 Integer small = tree.ceiling(nums[i]-t);//celing返回集合里>=指定元素的最小值 if((big!=null&&big>=nums[i])||(small!=null&&small<=nums[i])){ return true; } if(i>=k){ tree.remove(nums[i-k]); } tree.add(nums[i]); } return false; } }
时间: 2024-10-29 06:03:57