您的位置:首页 > 大数据 > 人工智能

【LeetCode】220. Contains Duplicate III

2016-10-18 07:40 351 查看
问题描述:

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.

即给定一个数组,判断是否该数组存在不同的下标i和j,满足abs(nums[i] - nums[j]) <= t and abs(i-j) <= k

解题思路:

这道题类似于滑动窗口问题,找出一个数与滑动窗口中的数值最近的距离是多少,滑动窗口的长度不超过t.

首先想到的思路是i从0到n-1迭代(n为数组的长度), 每次将nums[i]与nums[i]前面的k个数进行比较,时间复杂度为O(kn).

当k=n时,时间复杂度变为O(n^2),是否有更高效的方法呢?

STL里有一个类为multiset,类似set, 但multiset可以包含重复的元素,是使用红黑树来组织数据的.

multiset插入\删除元素的时间复杂度为O(logn),而且提供了lower_bound和upper_bound的功能,可以查找到一个数的下界和上界,时间复杂度也是O(logn).

lower_bound和upper_bound可以理解为,当我插入一个新的元素时,lower_bound是可以插入这个元素的第一个位置,也就是第一个大于等于该元素的位置.upper_bound是可以插入该元素的最后一个位置,也就是第一个大于该元素的位置.

以数组v为例子,int lo = lower_bound(v.begin(), v.end(), 4) - v.begin(); int up = upper_bound(v.begin(), v.end(), 4) - v.begin();

v = {3,4,4,5}时,lo=1, up = 3

v = {3,5}时,lo=1, up = 1

v = {1,2}时,lo=2, up = 2

v = {5,6}时,lo=0, up = 0

使用multiset类解决本题时,可以将以访问的数字添加到multiset中,将窗口外的数字移出multiset.

每检查一个元素,就在multiset中查找最靠近该元素的数字(时间复杂度O(log(n)) ),作一个比较.

最终时间复杂度为O(nlogn)

需要注意的是,测试数据存在nums大小小于等于1的情况,存在数据为2^31,用int类型相减时会发生溢出,因此需要使用long long类型进行运算.

参考代码:

#include <iostream>
#include <set>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (nums.size() <= 1)return false;
multiset<long long> se;
se.insert(nums[0]);
for (int i = 1;i < nums.size();++i){
if (se.size() > k)se.erase(se.find(nums[i-k-1]));
auto lo = se.lower_bound(nums[i]);
//auto up = se.upper_bound(nums[i]);
if (lo != se.end() && abs(*lo - nums[i]) <= t)return true;
if (lo != se.begin() && abs(*(--lo) - nums[i]) <= t)return true;
se.insert(nums[i]);
}
return false;
}
};


PS:

这道题也让我想起用两个栈来实现一个队列,求出滑动窗口中的最值的问题,时间复杂度为(O(n))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: