220. Contains Duplicate III

来源:互联网 发布:java之父 aws 编辑:程序博客网 时间:2024/06/05 06:05

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] andnums[j] is at mostt and the difference between i andj is at most k.

思路:

SortSet可以将添加进去的对象排序,subSet函数可以生成sortedSet(a,b)中【a,b)内的数据,维持一个长度为k的窗口,不断向后推进

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {       if (nums == null || nums.length <= 1 || k <= 0 || t < 0)               return false;       SortedSet<Long> set = new TreeSet<Long>();       for (int j = 0; j < nums.length; j++) {               SortedSet<Long> subSet = set.subSet((long) nums[j] - t,(long) nums[j] + t + 1);               if (!subSet.isEmpty())                       return true;               if (j >= k) {                       set.remove((long) nums[j - k]);               }       set.add((long)nums[j]);       }       return false;}


0 0