LeetCode 220. Contains Duplicate III

问题描述

  • Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
  • 地址

问题分析

  • 该题是LeetCode 219. Contains Duplicate II 进阶题目。又多了一个限制条件,不仅要求索引绝对值之差不超过 K, 还要求两数字绝对值之差不超过 t 。
  • 利用 滑动窗口 + TreeSet(底层实现是 BST) 来做,滑动窗口同样是保持窗口内的个数不超过 K个。而 TreeSet 用作存储窗口中的元素,可以直接借助 ceiling()函数floor()函数来定位到相应元素。具体见实现
  • 复杂度: O(NlogK)

经验教训

  • TreeSet 的 使用
    • ceiling(val)函数 返回集合中 >= val 的最小元素
    • ceiling(val)函数 返回集合中 <= val 的最大元素
  • 此题中的数据溢出问题
    • (long) nums[i] + t(long)nums[i] + t 的区别

代码实现

class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if (nums == null || nums.length == 0 || k < 0 || t < 0) {
            return false;
        }
        TreeSet<Long> set = new TreeSet<>();
        int left = 0;
        int right = 0;
        while (right < nums.length) {
            if (right - left > k) { //nums[right]的入窗导致窗口大小超过 k 个
                //左侧出窗
                set.remove((long)nums[left]);
                left++;
            }
            //待入窗元素nums[right],检查原窗口中是否存在[nums[right] - t, nums[right] + t]范围内的数
            Long ceilValue = set.ceiling(((long)nums[right] - t));
            if (ceilValue != null && ceilValue <= (long)nums[right] + t) {
                //若有,返回true
                return true;
            }
            //当前元素入窗
            set.add((long)nums[right]);
            //继续扩窗
            right++;
        }
        return false;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值