题目地址:
https://www.lintcode.com/problem/merge-k-sorted-arrays/description
给定若干升序排列的有序数组,要求返回一个数组,其元素为这些有序数组的所有数字,并且升序排列。
思路是类似归并排序。如果arrays长度为 ,那就直接返回了,否则的话就先合并左半边,再合并右半边,最后合并两个半边。代码如下:
public class Solution {
/**
* @param arrays: k sorted integer arrays
* @return: a sorted array
*/
public int[] mergekSortedArrays(int[][] arrays) {
// write your code here
if (arrays == null || arrays.length == 0) {
return new int[0];
}
return merge(arrays, 0, arrays.length - 1);
}
private int[] merge(int[][] arrays, int l, int r) {
if (l == r) {
return arrays[l];
}
int m = l + (r - l >> 1);
int[] a = merge(arrays, l, m), b = merge(arrays, m + 1, r);
int[] res = new int[a.length + b.length];
int i = 0, j = 0, idx = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
res[idx++] = a[i++];
} else {
res[idx++] = b[j++];
}
}
while (i < a.length) {
res[idx++] = a[i++];
}
while (j < b.length) {
res[idx++] = b[j++];
}
return res;
}
}
时空复杂度 。