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.


最开始想到的是暴力,双重循环,时间复杂度为O(nk)


这道题是滑动窗口的题。找满足|i-j| <= k 的nums,同时满足|nums[i] - nums[j]| <=t

即 -t <=nums[i] - nums[j] <= t, so nums[i] - t <= nums[j] <= nums[i]+t 

所以对于任意一个 nums[i] 只要满足在一个k长度的滑动窗口里即可

用set构造一个k长度的滑动窗口,然后每次检查[nums[i] - t, nums[i] + t]是否在是否包含在滑动窗口里,如果在那么说明存在另一个nums[j] 满足nums[i] - t <= nums[j] <= nums[i]+t ,且 i与j相差<=k

要注意数据范围,用long类型避免超int

代码如下:

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        set<long> window;
        if (nums.size() <=1  || t < 0 || k < 1) return false;
        for (int i = 0; i < nums.size(); i++) {
            if (i > k) window.erase(nums[i-k-1]); //更新滑动窗口
            auto pos = window.lower_bound(long(nums[i]) - t);//注意一定强制类型转换nums不然超int
            cout << *pos << endl;
            cout << nums[i]<<endl;
            if (pos != window.end() && *pos - nums[i] <= t) return true;  // 用*pos - nums[i] 不然 nums[i]+t超int
            window.insert(nums[i]);
        }
        return false;
        // for (int i = 0; i < nums.size() - k; i++) {
        //     for (int j = i + 1; j <= i + k; j++) {
        //         if (abs(nums[j] - nums[i]) <= t) return true;
        //     }
        // }
        // return false;
    }
};

学习使用set,set的底层数据结构是BST,所有元素都是有序的,lower_bound(num)返回第一个>=num的iterator,upper_bound(num)返回第一个>num的iterator。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值