LeetCode 220. Contains Duplicate III

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

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

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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值