您的位置:首页 > 编程语言 > Java开发

Java for LeetCode 220 Contains Duplicate III

2015-06-15 16:56 393 查看
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类型!

JAVA实现如下:

import java.util.*;
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if(nums==null || nums.length<2||k<1 || 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: