[LintCode] Nuts & Bolts Problem

java 4 2016-02-29 13:03


Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with nut to see which one is bigger/smaller.

We will give you a compare function to compare nut with bolt.


Given nuts = ['ab','bc','dd','gg'], bolts = ['AB','GG', 'DD', 'BC'].
Your code should find the matching bolts and nuts.

one of the possible return:

nuts = ['ab','bc','dd','gg'], bolts = ['AB','BC','DD','GG'].

we will tell you the match compare function. If we give you another compare function.
the possible return is the following:

nuts = ['ab','bc','dd','gg'], bolts = ['BC','AA','DD','GG'].

So you must use the compare function that we give to do the sorting.
The order of the nuts or bolts does not matter. You just need to find the matching bolt for each nut.


两次排序 O(n^2)

public class Solution {  
    public void sortNutsAndBolts(String[] nuts, String[] bolts, NBComparator compare) {  
        // write your code here  
         for(int i=0;i<nuts.length;i++){  
              for(int j=i;j<bolts.length;j++){  
                   if(compare.cmp(nuts[i], bolts[j])==0){  
                        String tmp = bolts[i];  
                        bolts[i] = bolts[j];  
                        bolts[j] = tmp;