我正在尝试实现一种算法,以一种天真的方式故意合并 k sorted 数组(每个 n 元素):
步骤:
我的代码可以为3x3,4x4,5x5 2D数组输出已排序的单个数组,但是当2D数组变为6x6时,它会卡住。
是不是因为代码的复杂性太差而且编译时间太长?或者有一些我不知道的愚蠢逻辑错误?
我读完了我的代码,我猜这个问题是我用“<<<< ==== ??”标记的行。我怎样才能做对吗?
public class Merge {
// merge 2 arrays into a single sorted array
private static int[] merge(int[] arrayA, int[] arrayB) {
int n1 = arrayA.length; // number of elements in arrayA
int n2 = arrayB.length; // number of elements in arrayB
int[] mergeArray = new int[n1+n2];
int i = 0; // pointer of current index in mergeArray
int p1 = 0; // pointer of current index in arrayA
int p2 = 0; // pointer of current index in arrayB
while (p1 < n1 && p2 < n2) {
// put the lowest number the mergeArray until one of the array is done
if (arrayA[p1] < arrayB[p2]) {
mergeArray[i] = arrayA[p1];
i++;
p1++;
}
else if (arrayB[p2] < arrayA[p1]) {
mergeArray[i] = arrayB[p2];
i++;
p2++;
}
}
// if all elements of arrayA is copied to mergeArray, then copy remaining elements in arrayB to it
if (p1 >= n1) {
for (int j = p2; j < arrayB.length; j++) {
mergeArray[i] = arrayB[j];
i++;
}
}
// if all elements of arrayB is copied to mergeArray, then copy remaining elements in arrayA to it
if (p2 >= n2) {
for (int j = p1; j < arrayA.length; j++) {
mergeArray[i] = arrayA[j];
i++;
}
}
return mergeArray;
}
public static int[] naiveMerge(int[][] data) {
int k = data.length; // number of sorted array
int n = data[0].length; // number of elements in each array
int[] resultArray = new int[k*n];
int[] tempArray = Merge.merge(data[0], data[1]); // merge the first two arrays
for (int i = 2; i < k; i++) {
// then merge in the third, fourth ... k arrays
tempArray = Merge.merge(tempArray, data[i]); // <<<==== ??
resultArray = tempArray;
}
return resultArray;
}
}
答案 0 :(得分:2)
如果你看一下3,4和5的数组,你会发现,纯粹巧合的是,所有数组中的所有数值都是唯一的。但是,在您的6个案例中,请注意有重复的值(其中有两个46&#39;)。追踪while
中的第一个merge
循环。如果两个数组在某个时刻恰好具有相同的值,会发生什么?