Merge k Sorted Arrays
Given k sorted integer arrays, merge them into one sorted array.
Challenge
Do it in O(N log k).
- N is the total number of integers.
- k is the number of arrays.
思路: 1.合并成1个数组,调用快速排序。 时间复杂度 O(NlogN + N)
2.二分法 + merge 时间复杂度O(Nlogk)。
1 public class Solution { 2 /** 3 * @param arrays k sorted integer arrays 4 * @return a sorted array 5 */ 6 public List<Integer> mergekSortedArrays(int[][] arrays) { 7 List<Integer> list = new ArrayList<>(); 8 if (arrays == null || arrays.length == 0) { 9 return list; 10 } 11 int[] tmp = mergeHelper(arrays, 0 , arrays.length - 1); 12 for (int i = 0; i < tmp.length; i++) { 13 list.add(tmp[i]); 14 } 15 return list; 16 } 17 18 private int[] mergeHelper(int[][] arrays, int begin, int end) { 19 if (begin >= end) { 20 return arrays[begin]; 21 } 22 int mid = begin + (end - begin) / 2; 23 int[] a = mergeHelper(arrays, begin, mid); 24 int[] b = mergeHelper(arrays, mid + 1, end); 25 return merge(a, b); 26 } 27 28 private int[] merge(int[] a, int[] b) { 29 int len = a.length + b.length; 30 int[] result = new int[len]; 31 int i = 0, j = 0, k = 0; 32 for (k = 0; k < len; k++) { 33 if (i < a.length && (j == b.length || a[i] < b[j])) { 34 result[k] = a[i]; 35 i++; 36 } else { 37 result[k] = b[j]; 38 j++; 39 } 40 } 41 return result; 42 43 } 44 }