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;
    }
}

 

posted @ 2015-06-28 06:11  dshao  阅读(150)  评论(0编辑  收藏  举报