您的位置:首页 > 产品设计 > UI/UE

coursera Algorithms week1 Interview Questions

2018-02-06 16:19 169 查看
题目2:

Union-find with specific canonical element. Add a method find() to
the union-find data type so that find(i) returns
the largest element in the connected component containing i.
The operations, union(), connected(),
and find() should
all take logarithmic time or better.

For example, if one of the connected components is {1,2,6,9},
then the find()method
should return 9 for
each of the four elements in the connected components.

分析:

与加权 quick-union算法思路大概一致,在union()方法中进行根节点的控制,使得根节点始终是最大的数。

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class UF {
private int[] id;	//分量id
private int count;	//分量数量

public UF(int N) {
//初始化分量id数组
count = N;
id = new int
;
for (int i = 0; i < N; i++)
id[i] = i;
}

public int count() {
return count;
}

public boolean connected(int p, int q) {
return find(p) == find(q);
}

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

public void union(int p, int q) {
int i = find(p);
int j = find(q);
if (i == j)
return;
if (i > j)
id[j] = i;
else
id[i] = j;
count--;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
//解决由S
4000
tdIn得到的动态连通性问题
int N = StdIn.readInt();
UF uf = new UF(N);
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt();
if (uf.connected(p, q))	continue;
uf.union(p, q);
StdOut.println(p + "" + q);
}
StdOut.println(uf.count() + "components");
}
}



题目三:

Successor with delete. 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) take logarithmic time or better in the worst case.

分析:

是对题目2的应用;每次remove(x)都是将 x 和 x + 1 进行连接,每次remove(x)会使数组的x消失可以等价成寻找根节点的模型。getsuccessor(x)即是返回 x 的根节点。

import edu.princeton.cs.algs4.StdOut;

public class Successor {
private int[] id; //父链接索引
public Successor(int N) {
id = new int
;
for(int i = 0; i < N; i++)
id[i] = i;
}
public int find(int p) {
//找到根节点
while(p != id[p])
p = id[p];
return p;
}
public void remove(int p) {
union(p, p + 1);
}
public void union(int p, int q) {
int i = id[p];
int j = id[q];
if (i == j)
return;
//将较大的数作为根节点
else if (i > j)
id[q] = i;
else
id[p] = j;
}
public int getsuccessor(int p) {
return find(p);
}
public static void main(String[] args) {
Successor s = new Successor(10);
s.remove(6);
s.remove(5);
s.remove(3);
StdOut.println("the successor of 3 is " + s.getsuccessor(3));
s.remove(4);
s.remove(7);
StdOut.println("the successor of 3 is " + s.getsuccessor(3));
StdOut.println("the successor of 1 is " + s.getsuccessor(1));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Algorithms Coursera