Leetcode 220. Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

 
 
 
思路:维持一个大小为k的窗口,由左向右在nums中移动。对于nums[i],只要查找其之前的元素中是否存在大小范围在[nums[i] - t,nums[i] + t]的元素,如果存在就返回true。还要注意整数的溢出问题,比如下面的测试用例:
[0,2147483647]
1
2147483647
 
代码:
 1 public class Solution {
 2     public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
 3         if (nums == null || nums.length == 0 || k <= 0)
 4             return false;
 5         TreeSet<Long> ts = new TreeSet();
 6         for (int i = 0; i < nums.length; ++i) {
 7             Long right = ts.floor((long) nums[i] + t);
 8             Long left = ts.ceiling((long) nums[i] - t);
 9             if (right != null && left != null && right >= left)
10                 return true;
11             ts.add((long) nums[i]);
12             if (i >= k)//i >= k说明nums[i]之前至少已经有k各不相同的元素(否则早就返回true)
13                 ts.remove((long) nums[i - k]);
14 //             //将上面的if改写成以下条件也是正确
15 //             if (ts.size() >= k)//
16 //                 ts.remove((long) nums[i - k]);
17 
18         }
19         return false;
20     }
21 }

 

posted @ 2017-03-24 14:22  Deribs4  阅读(665)  评论(0编辑  收藏  举报