Leetcode: Contains Duplicate III
2015-12-18 23:31
363 查看
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类型!
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 i=0; i<nums.length; i++) { long lowerBound = (long)nums[i]-t; long upperBound = (long)nums[i]+t+1; SortedSet<Long> temp = set.subSet(lowerBound, upperBound); if (!temp.isEmpty()) { return true; } set.add((long)nums[i]); if (set.size() > k) set.remove((long)nums[i-k]); } return false; } }
时间 O(NlogK) 空间 O(K)
思路
要求判断之前是否存在差值小于t的数字,我们需要知道在当前数字x两边的数字,即最大的小于x的数字和最小的大于x的数字。二叉搜索树有也有这样的性质,它的左子树的最右节点是最大的较小值,右子树的最左节点是最小的较大值。这里我们用TreeSet这个类,它实现了红黑树,并有集合的性质,非常适合这题。我们同样也是维护一个大小为k的TreeSet,多余k个元素时把最早加入的给删除。用ceiling()和floor()可以找到最小的较大值和最大的较小值。public class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { TreeSet<Integer> set = new TreeSet<Integer>(); for(int i = 0; i < nums.length; i++){ int x = nums[i]; // 最大的小于x的数字 if(set.ceiling(x) != null && set.ceiling(x) <= t + x) return true; // 最小的大于x的数字 if(set.floor(x) != null && x <= t + set.floor(x)) return true; set.add(x); if(set.size()>k) set.remove(nums[i-k]); } return false; } }
相关文章推荐
- sizeof(数组名)和sizeof(指针) http://blog.csdn.net/kangroger/article/details/20653255
- Daily Scrum NO.7
- Auto Layout(NSLayoutConstraint)
- ERROR: dependency ‘plyr’ is not available for package ‘scales’
- HDU 1082 Matrix Chain Multiplication 逆波兰式
- uva 12222——Mountain Road
- Redhat6.4 软raid磁盘更换
- Unable to save settings: Failed to save settings. Please restart IntelliJ IDEA 解决方法
- Factorial Trailing Zeroes
- error: device not found - waiting for device -
- destoon去掉会员注册email验证
- HDOJ&nbsp;&nbsp;4300&nbsp;&nbsp;&nbsp;Clairewd’s&nbsp;message
- HDOJ&nbsp;&nbsp;1022&nbsp;&nbsp;&nbsp;Train&nbsp;Problem&nbsp;I
- HDOJ&nbsp;&nbsp;&nbsp;1021&nbsp;&nbsp;&nbsp;&nbsp;Fibonacci&nbsp;Again
- pair和make_pair用法
- [转]strong,weak, retain, assign的区别
- macbook air 只安装win7系统
- 详解Paint的setShader(Shader shader)
- 如何解决SVN Commit failed (details follow): Access denied
- LeetCode 172:Factorial Trailing Zeroes