*LeetCode-Contains Duplicate III
2015-10-06 06:20
483 查看
本来想像第二道题一样用一个k 大小的set维持一个连续的window 然后每次取这个set最大值最小值 然后和下一个数取diff
但是超时了
需要用tree set 有两个很有用的function floor 和 ceiling 分别
Returns the greatest element in this set less than or equal to the given element, or
there is no such element.
Returns the least element in this set greater than or equal to the given element, or
there is no such element.
所以判断条件是 找到这样的floor 并且floor的方向正确 大于num[i]即表示在num [ i ]到 num[ i ] + k找到了一个数
或者找到了在num [ i ] -k 到 num[ i ] 找到了一个数
注意每次先判断这些 然后没有return的话 add这个num[i]然后假如个数超了 就remove头上一个
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Integer> set = new TreeSet<Integer>();
if ( nums == null || nums.length == 0 || k <= 0 )
return false;
for ( int i = 0; i < nums.length; i ++ ){
Integer floor = set.floor ( nums[i] + t );
Integer ceiling = set.ceiling ( nums[i] - t );
if ( (floor != null && floor >= nums[i]) || (ceiling != null && ceiling <= nums[i]) )
return true;
set.add ( nums[ i ] );
if ( i >= k ){
set.remove( nums[ i - k ] );
}
}
return false;
}
}
但是超时了
需要用tree set 有两个很有用的function floor 和 ceiling 分别
Returns the greatest element in this set less than or equal to the given element, or
nullif
there is no such element.
Returns the least element in this set greater than or equal to the given element, or
nullif
there is no such element.
所以判断条件是 找到这样的floor 并且floor的方向正确 大于num[i]即表示在num [ i ]到 num[ i ] + k找到了一个数
或者找到了在num [ i ] -k 到 num[ i ] 找到了一个数
注意每次先判断这些 然后没有return的话 add这个num[i]然后假如个数超了 就remove头上一个
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Integer> set = new TreeSet<Integer>();
if ( nums == null || nums.length == 0 || k <= 0 )
return false;
for ( int i = 0; i < nums.length; i ++ ){
Integer floor = set.floor ( nums[i] + t );
Integer ceiling = set.ceiling ( nums[i] - t );
if ( (floor != null && floor >= nums[i]) || (ceiling != null && ceiling <= nums[i]) )
return true;
set.add ( nums[ i ] );
if ( i >= k ){
set.remove( nums[ i - k ] );
}
}
return false;
}
}
相关文章推荐
- Privileged containers provisioning by Kubernetes in Ubuntu
- usaco Snail Trails
- 《ZHU, MAI, SHAO: SINGLE IMAGE DEHAZING USING COLOR ATTENUATION PRIOR》关于此文的理解与实现
- hdoj 1022 Train Problem I
- [codeforces 582b]Once Again…
- 11 Container With Most Water
- 有关人工智能
- Codeforces Round #323 D Once Again...
- 二进制“<<”: 没有找到接受“const std::basic_string<char,std::char_traits<char>,std::allocator<char>>”类型的右操作数的运算
- DLLMain函数
- autofac获取全局Container
- main函数中两个参数的用法
- 2014 Asia Shanghai Regional Contest H
- Raid管理详解
- 【static&extern,有心得】staitc在C中,修饰函数.(让我明白了,在include该文件后,则该文件的static也可见了)
- 2014 Asia Shanghai Regional Contest J
- 矩阵快速幂 CodeForces - 582B Once Again...
- codeforces 583B B. Once Again...(dp)
- HDU 4810 Wall Painting(组合数学)
- LightOJ 1282 Leading and Trailing