Given a set of N integers S={0,1,…,N−1} and a sequence of requests of the following form:
- Remove x from S
- Find the successor of x: the smallest y in S such that y≥x.
- design a data type so that all operations (except construction) should take logarithmic time or better.
问题描述
Given a set of N integers S={0,1,…,N−1} and a sequence of requests of the following form: - Remove x from S
- Find the successor of x: the smallest y in S such that y≥x.
- design a data type so that all operations (except construction) should take logarithmic time or better.
思路分析
首先来看题目要求是对数时间,这样的话肯定不可能遍历完整个数组(这样至少为n),加之这一部分学的是并查集。。所以思考怎么使用并查集来解决这个问题。这个问题思考了很久啊。。一直没有答案,这里不得不吐槽一下国内写的博客。。完全是为自己写的,应该只有作者本人可以看懂。。。不扯了,接下来借鉴了墙外的一些思路来写的。
当确定这个题可能要使用并查集的时候我们再来仔细分析一下要求,首先给定的是一段连续的自然数序列(或者数组下标);第二点我们要获取移除的successor: 剩余数中大于数的队列中的最小数。我们来举个例子,
{1 …8}在这八个数中我们移除6,6的successor为7(find(6) ==7);
再移除5,find(5) == 7;
再移除2 , find(2) == 3 find(3) = 3 find(5) ==7
我们可以看到输出的值为一个连通域中最大值+1,而这个连通域由我们remove()的数组成。这就想起了上一道题,我们使用并查集来实现在对数时间中查找列表中的最大项。
代码
|
|
输出:
the successor is : 5
参考文章
http://vancexu.github.io/2015/07/21/intro-to-union-find-data-structure-exercise.html(墙内)