1.Intersection of two sets. Given two arrays a[] and b[], each containing n distinct 2D points in the plane, design a subquadratic algorithm to count the number of points that are contained both in array a[] and array b[].
描述:以小于平方级别级别复杂度求出两个Points数组的并里面的元素数目。
解答:对b排序,对于a里面的每个元素,利用二分查找在b里面寻找是否有相同Point,如果有,数组增加1。这种解决方法复杂度可以保持在nlogn, 代码如下,Point类自己定义。
public class IntersectionOfArray {
public static int intersection(Point[] a, Point[] b) {
Quick.sort(b);
int length = b.length;
int count = 0;
for (Point point : a) {
if (BinarySearch.indexOf(b, 0, length - 1, point) != -1) {
count++;
}
}
return count;
}
public static void main(String[] args) {
Point p1 = new Point(1.0, 1.0);
Point p2 = new Point(1.0, 4.0);
Point p3 = new Point(3.0, 1.0);
Point p4 = new Point(5.0, 1.0);
Point p5 = new Point(1.0, 1.0);
Point p6 = new Point(1.0, 4.0);
Point p7 = new Point(3.0, 1.0);
Point p8 = new Point(7.0, 2.0);
Point[] aPoints = {p1, p2, p3, p4};
Point[] bPoints = {p5, p6, p7, p8};
int count = intersection(aPoints, bPoints);
StdOut.print(count);
}
}
2.Permutation. Given two integer arrays of size n, design a subquadratic algorithm to determine whether one is a permutation of the other. That is, do they contain exactly the same entries but, possibly, in a different order.
描述:以小于平方级别级别复杂度两个整型数组是不是另外一个的排列组合。
解答:分别排序,再一一比较,如果有一个不同,返回false, 否则返回true,复杂度nlogn。
3.Dutch national flag. Given an array of n buckets, each containing a red, white, or blue pebble, sort them by color. The allowed operations are:
- swap(i,j): swap the pebble in bucket i with the pebble in bucket j.
- color(i): color of pebble in bucket i.
- At most n calls to color().
- At most n calls to swap().
- Constant extra space.
描述:荷兰国旗三色排序问题。
解答:利用3-way的快排的变式即可,详情看算法第四版。