[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