您的位置:首页 > 大数据 > 人工智能

LeetCode 220. Contains Duplicate III

2020-07-26 13:44 726 查看

可以用TreeSet来解决问题,但是为了防止溢出的问题,必须将类型强制转化成long(对应的包装类为Long)。

https://leetcode-cn.com/problems/contains-duplicate-iii/solution/hua-dong-chuang-kou-er-fen-sou-suo-shu-zhao-shang-/

[code]class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
// Corner case
if(nums == null || nums.length == 0){
return false;
}
TreeSet<Long> set = new TreeSet<>();
// Sliding window
for(int i = 0; i < nums.length; i++){
// Remove the element of which the distance is larger than k
if(i > k){
set.remove((long) nums[i - k - 1]);
}
// Get the least element which is larger than or equal to the given number
Long ceiling = set.ceiling((long) nums[i] - t);
// Be cautious of the condition in which the return value is null
if(ceiling != null && ceiling <= (long) nums[i] + t){
return true;
}
// Add the curren element into the set
set.add((long) nums[i]);
}
return false;
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: