Interview - sort

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.
The performance requirements are as follows:
  • At most n calls to color().
  • At most n calls to swap().
  • Constant extra space.

描述:荷兰国旗三色排序问题。
解答:利用3-way的快排的变式即可,详情看算法第四版。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值