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

Leetcode: Contains Duplicate III

时间:2015-12-19 00:15:16      阅读:213      评论: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.

暴力枚举会LTE,解题思路是用sortedSet来解决,sortedSet可以返回一个在某个范围的subSet,同时判断这个subSet是否为空即可解决,主要,本题需要使用long类型!

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

 

Leetcode: Contains Duplicate III

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5058469.html

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