Problem
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.
Example
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.
Solution
两次排序 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;
break;
}
}
}
}
}
Quick Sort
public void sortNutsAndBolts(String[] nuts, String[] bolts, NBComparator compare) {
// write your code here
sort(nuts,bolts,0,nuts.length-1, compare);
}
public void sort(String[] nuts, String[] bolts, int l, int h, NBComparator compare) {
if(l < h){
int p = partition(nuts, l,h, bolts[h], compare);
partition(bolts, l,h,nuts[p], compare);
sort(nuts, bolts, l, p-1,compare);
sort(nuts, bolts, p+1, h,compare);
}
}
public int partition(String[] strs, int l, int w, String pivot, NBComparator compare) {
int j = l-1;
for (int i = l; i < w; i++) {
if (compare.cmp(strs[i], pivot) == -1 || compare.cmp(pivot, strs[i]) == 1) {
j++;
swap(strs, i, j);
} else if (compare.cmp(strs[i], pivot) == 0 ||compare.cmp(pivot, strs[i]) == 0) {
swap(strs, i, w);
i--;
}
}
j++;
swap(strs, j,w);
return j;
}
private void swap(String[] a, int i, int j) {
String temp = a[i];
a[i] = a[j];
a[j] = temp;
}
本文介绍了一种特殊的排序问题——如何为不同大小的螺母找到对应的螺栓。通过两种算法实现:低效的二次排序方法和高效的快速排序方法。文章详细展示了这两种算法的具体实现过程。
1695

被折叠的 条评论
为什么被折叠?



