您的位置:首页 > 编程语言 > Go语言

Coursera Algorithms week1 练习测验3:Successor with delete

2017-07-18 09:47 239 查看
题目原文:

Given a set of n integers S = {0,1,…,N-1}and a sequence
of requests of the following form:

Remove x from SFind the successor of x: the smallest y in S such thaty>=x

design a data type so that all operations(except construction) take logarithmic time or better in the worst case.

分析

题目的要求有一个0~n-1的顺序排列序列S,从S中移除任意x,然后调用getSuccessor(x),方法将返回一个y,这个y是剩余还在S中满足y>=x的最小的数。举例说明S={0,1,2,3,4,5,6,7,8,9}时

remove 6,那么getSuccessor(6)=7

remove 5,那么getSuccessor(5)=7

remove 3,那么getSuccessor(3)=4

remove 4,那么getSuccessor(4)=7

remove 7,那么getSuccessor(7)=8, getSuccessor(3)=8

而对于没有remove的数x,getSuccessor(x)应该等于几呢?题目没有说,那么就认为等于自身好了,接着上面,getSuccessor(2)=2

根据上面的例子,可以看出,实际上是把所有remove的数做了union,root为子集中的最大值,那么getSuccessor(x)实际就是获取remove数中的最大值+1,根据这个思路,代码如下

package UF;

import edu.princeton.cs.algs4.StdOut;

public class Successor {
private int num;
private int[] id;
private boolean[] isRemove;

public Successor(int n){
num = n;
id = new int
;
isRemove = new boolean
;
for (int i = 0; i < n; i++) {
id[i] = i;
isRemove[i] = false;
}
}

public int find(int p) {
while (p != id[p])
p = id[p];
return p;
}

public void union(int p, int q) {
//此处的union取较大根
int pRoot = find(p);
int qRoot = find(q);
if (pRoot == qRoot)
return;
else if (pRoot < qRoot)
id[pRoot] = qRoot;
else
id[qRoot] = pRoot;
}

public void remove(int x) {
isRemove[x] = true;
//判断相邻节点是否也被remove掉了,如果remove掉就union
if (x>0 && isRemove[x-1]){
union(x,x-1);
}
if (xnum-1){//越界异常
throw new IllegalArgumentException("访问越界!");
}else if(isRemove[x]){
if(find(x)+1 > num-1) //x以及大于x的数都被remove掉了,返回-1
return -1;
else //所有remove数集中最大值+1,就是successor
return find(x)+1;
}else {//x未被remove,就返回x自身
return x;
}
}

public static void main(String[] args) {
Successor successor = new Successor(10);
successor.remove(2);
successor.remove(4);
successor.remove(3);
StdOut.println("the successor is : " + successor.getSuccessor(3));
successor.remove(7);
successor.remove(9);
StdOut.println("the successor is : " + successor.getSuccessor(9));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐