Google interview question: quickSort-like questions

上一篇总结了mergeSort-like questions,这篇总结一下有关quickSort的问题。

Question: 

Given an array of object A, and an array of object B. All A's have 
different sizes, and all B's have different sizes. Any object A is of the 
same size as exactly one object B. We have a function f(A, B) to compare the 
size of one A and one B. But we cannot compare between two A's or two B's. 
Give an algorithm to match each A with each B.

Brute force的做法时间复杂度是O(N^2)。这个问题的本质是利用quickSort来进行matching,平均时间复杂度为O(Nlog(N))。因为相同的数组之间不能进行比较,所以需要在一个数组中选出一个元素,作为另一个数组的pivot进行划分,然后递归直到所有元素都一一对应。这个问题也叫做matching nuts & bolts。

public class MatchingNutsAndBolts {
    public static void main(String arcg[]){
        int[] nuts = {3,1,5,2,6,4};
        int[] bolts = {5,1,2,6,4,3};
        matchPairs(nuts,bolts,0,nuts.length-1);
        System.out.println(Arrays.toString(nuts));
        System.out.println(Arrays.toString(bolts));
    }
    public static void matchPairs(int[] nuts, int[] bolts, int low, int high){
        if(low < high){
            int pivot = partition(nuts, low, high, bolts[low]);
            partition(bolts, low, high, nuts[pivot]);
            matchPairs(nuts, bolts, low, pivot-1);
            matchPairs(nuts, bolts, pivot+1, high);
        }
    }
    public static int partition(int[] array, int low, int high, int pivot){
        int i=low,j = high;
        while(i<=j){
            if(array[i] > pivot){
                swap(array, i, j);
                j--;
            }
            else if(array[i] < pivot){
                i++;
            }
            else{
                swap(array, low, i);
                i++;
            }
        }
        swap(array, low, i-1);
        return i-1;
    }
    public static void swap(int[] array, int i, int j){
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
}

 

转载于:https://www.cnblogs.com/dshao/p/4605065.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值