[LeetCode] Contains Duplicate III

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] and nums[j] is at most t and the difference between i and j is at most k.

一开始理解错题目了,还以为是要求所有的数对都必须符合要求,一直超时。其实题目是问是不是存在一个符合条件的数对,所以就容易多了,维护一个大小为 k 的二叉搜索树,来一个新的元素时,在BST上二分搜索有没有符合条件的数对,动态更新这个BST。因为BST的大小为 k 或不超过 k,所以这里面的数下标的差值一定是符合条件的。还有几点要注意的就是nums[i]与nums[j]的差值的是绝对值,所以要分别找lower_bound跟upper_bound,数据比较坑爹,为了防止溢出,容器用long long类型的。

 1 class Solution {
 2 public:
 3     bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
 4         multiset<long long> bst;
 5         for (int i = 0; i < nums.size(); ++i) {
 6             if (bst.size() == k + 1) bst.erase(bst.find(nums[i - k - 1]));
 7             auto lb = bst.lower_bound(nums[i]);
 8             if (lb != bst.end() && abs(*lb - nums[i]) <= t) return true;
 9             auto ub = bst.upper_bound(nums[i]);
10             if (ub != bst.begin() && abs(*(--ub) - nums[i]) <= t) return true;
11             bst.insert(nums[i]);
12         }
13         return false;
14     }
15 };

 

不用比较两次,直接找nums[i] - t的lower_bound, 这个值就是与nums[i]差值最近的值。

 1 class Solution {
 2 public:
 3     bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
 4         multiset<long long> bst;
 5         for (int i = 0; i < nums.size(); ++i) {
 6             if (bst.size() == k + 1) bst.erase(bst.find(nums[i - k - 1]));
 7             auto lb = bst.lower_bound(nums[i] - t);
 8             if (lb != bst.end() && *lb - nums[i] <= t) return true;
 9             bst.insert(nums[i]);
10         }
11         return false;
12     }
13 };

 

转载于:https://www.cnblogs.com/easonliu/p/4544073.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值