【题目】
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.
【分析】
1. 一直在想用HashMap解决问题,没办法。用了TreeSet(实现了SortedSet接口),SortedSet有个subSet(from, to)方法比较有效
2. 主要需要比较坐标和元素值,使Set里最多只有k个元素,每加入一个元素,判断是否有两个元素的元素值之差小于t
【算法实现】
public boolean solution(int[] nums, int k, int t) { boolean b = false; TreeSet<Long> s = new TreeSet<Long>(); for(int i=0; i<nums.length; i++) { TreeSet<Long> sub = (TreeSet)s.subSet(nums[i]-t, true, nums[i]+t, true); if(!sub.isEmpty()) return true; if(i >= k) { s.remove((long)nums[i-k]); } s.add((long)nums[i]); } return false; }