这似乎是O(n log(k)),其中k是网格的宽度,n是深度(假设平滑网格或网格中元素的总数,如果它是锯齿状的)。这是对的吗?
public class KWayMerge {
private int[] merge(int[][] grid) {
return merge(grid, 0, grid.length - 1);
}
// O(n log k) wehre k is the width of the grid and n is the depth (assuming smooth grid)
private int[] merge(int[][] grid, int start, int end) {
if (end == start) {
return grid[end];
} else if (end - start == 1) {
return merge(grid[end], grid[start]);
} else {
return merge(merge(grid, start, (end + start) / 2), merge(grid, ((end + start) / 2) + 1, end));
}
}
private static int[] merge(int[] left, int[] right) {
int[] result = new int[left.length + right.length];
int lPos = 0, rPos = 0, pos = 0;
while(true) {
if (lPos >= left.length) {
System.arraycopy(right, rPos, result, pos, right.length - rPos);
break;
} else if (rPos >= right.length) {
System.arraycopy(left, lPos, result, pos, left.length - lPos);
break;
}
if (left[lPos] < right[rPos]) {
result[pos] = left[lPos];
lPos++;
} else {
result[pos] = right[rPos];
rPos++;
}
pos++;
}
return result;
}
}
答案 0 :(得分:0)
您的复杂度O(N K LogK)
例如,您有8个大小为N的数组:
您将进行以下合并: 迭代#1:
迭代#2:
迭代#3: 1. 12345678(8 * N)
共: 你有以下复杂性 K / 2 *(2 * N) K / 4 *(4 * N) K / 8 *(8 * N)
每个= K * N和LogK计数。
总复杂度将为 O(KN * LogK)
其中K个数组,N
是数组的平均大小。