我从https://www.programmerall.com/article/7941762158/找到了一个解决方案
我有一些改变。
题目要求有一个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, then getSuccessor(6)=7
remove 5, then getSuccessor(5)=7
remove 3, then getSuccessor(3)=4
remove 4, then getSuccessor(4)=7
remove 7, then getSuccessor(7)=8, getSuccessor(3)=8
根据上面的例子可以看出,其实就是把所有被移除的数都做成了一个union,而root是子集中的最大值,那么getSuccessor(x)其实就是获取remove的最大值数字 + 1。
对于没有删除的数字 x,应该getSuccessor(x)
等于什么?会有3种情况:
Case1:数字本身是最后一个数字,返回自身。
Case2:下一个数不去掉,返回x+1。
Case3:下一个数被移除,返回移除数的最大值+1
JAVA代码如下。
public class Successor {
private int num;
private int[] id;
private boolean[] isRemove;
public Successor(int n) {
num = n;
id = new int[n];
isRemove = new boolean[n];
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) {
// The union here takes the larger root
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;
// Determine whether the adjacent node is also removed by remove, if remove is
// removed, union
if (x > 0 && isRemove[x - 1]) {
union(x, x - 1);
}
if (x < num - 1 && isRemove[x + 1]) {
union(x, x + 1);
}
}
public int getSuccessor(int x) {
if (x < 0 || x > num - 1) {// Out-of-bounds anomaly
throw new IllegalArgumentException("Access out of bounds!");
} else if (isRemove[x]) {
if (find(x) + 1 > num - 1) // x and the number greater than x are removed, return -1
return -1;
else // The maximum value of all the remove numbers is +1, which is the successor
return find(x) + 1;
} else if (x == num - 1) {// the last elmemnet, return itself.
return x;
} else if (isRemove[x + 1]) { // if the next element is removed, return The maximum value of all the remove
// numbers is +1, which is the successor
return find(x + 1) + 1;
} else { // if the next element is not removed && itself is not removed, return next
// element.
return x + 1;
}
}
public static void main(String[] args) {
Successor successor = new Successor(10);
successor.remove(2);
successor.remove(4);
successor.remove(3);
System.out.println("the successor is : " + successor.getSuccessor(3));
successor.remove(7);
System.out.println("the successor is : " + successor.getSuccessor(0));
System.out.println("the successor is : " + successor.getSuccessor(1));
System.out.println("the successor is : " + successor.getSuccessor(9));
}
}