码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Contains Duplicate III

时间:2015-10-31 06:55:22      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

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.

SOL1:

 1 public class Solution {
 2     public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
 3         if(nums == null || nums.length == 0 || t < 0)
 4             return false;
 5         TreeSet<Long> ts = new TreeSet<>();
 6         for(int i = 0; i < nums.length; ++i) {
 7             if(i > k)
 8                 ts.remove((long)nums[i - k - 1]);
 9             TreeSet<Long> temp = (TreeSet<Long>) ts.subSet((long)nums[i] - t, true,(long)nums[i] + t, true);
10             if(!temp.isEmpty())
11                 return true;
12             ts.add((long)nums[i]);
13         }
14         return false;
15     }
16 }

 

SOL2:

利用bucket来做:

https://leetcode.com/discuss/38206/ac-o-n-solution-in-java-using-buckets-with-explanation

[Leetcode] Contains Duplicate III

标签:

原文地址:http://www.cnblogs.com/Phoebe815/p/4924766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!