[leetcode] 220. Contains Duplicate III 解题报告

题目链接:https://leetcode.com/problems/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 difference between nums[i] andnums[j] is at most t and the difference between i and j is at most k.

思路:这题我们需要寻找的两个数满足: -t <= nums[i] - nums[j] <= t,一个比较直观的解法是两重循环,维护一个k大小的窗口,这种时间复杂度是O(N^2),是过不了所有测试数据的。可以优化的地方在于一个窗口中怎么寻找满足这个条件的两个位置。我们可以将一个窗口中的数据构造一个二叉排序数,向树中插入、删除、查找数据的时间复杂度是O(log(N)),因此可以将时间复杂度降为O(N*log(N))。

假设当前遍历到nums[i],另一个数大小为x,我们要在二叉排序树中找到是否有满足: nums[i] - t <= x <= nums[i] + t 的位置。在C++的STL中提供了二叉排序树的数据结构set,并且其提供了一个函数lower_bound,可以查找树中第一个大于等于某值的位置,利用这个函数可以找到第一个大于等于nums[i]-t的指针,然后再判断其值是否满足条件即可。

代码如下:

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        if(nums.size() ==0) return false;
        multiset<int> st;
        for(int i = 0; i < nums.size(); i++)
        {
            if(i > k) st.erase(st.find(nums[i-k-1]));
            auto it = st.lower_bound(nums[i]-t);
            if(it!=st.end() && abs(*it-nums[i]) <=t) return true;
            st.insert(nums[i]);
        }
        return false;
    }
};

 参考:https://leetcode.com/discuss/45120/c-using-set-less-10-lines-with-simple-explanation

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值