題目:合並N個有序數組,每個數組的長度為M,合並為N*M的有序數組。時間復雜度要求最低
解法:N個數組進行兩兩合並,合並后的數組再繼續執行合並過程,最后合成N*M的有序數組。可以認為合並這個遞歸過程發生了logN次,每一次合並的過程都是N*M個數合並,所以每一次合並的時間復雜度為N*M,總的時間復雜度就是N*M*logN
代碼如下:
public class MergeArrays { public static void main(String[] args) { int[][] nums = new int[][]{{1, 5, 11, 23}, {3, 6, 8, 20}, {2, 4, 7, 15}, {9, 10, 19, 28}}; for (int num : mergeArrays(nums)) { System.out.print(num + " "); } } //將N個數組合並為一個數組 public static int[] mergeArrays(int[][] nums) { return merge(nums); } //兩兩合並數組 public static int[] merge(int[][] nums) { if (nums.length == 0) { return null; } if (nums.length == 1) { return nums[0]; } int rows = nums.length / 2; //兩兩合並后的新數組 int[][] result = new int[rows][]; for (int i = 0; i < nums.length; i += 2) { result[i / 2] = mergeTwoArray(nums[i], nums[i + 1]); } return merge(result); } //具體對兩個數組進行合並,成為一個新數組 public static int[] mergeTwoArray(int[] nums1, int[] nums2) { int length1 = nums1.length; int length2 = nums2.length; int[] helper = new int[length1 + length2]; int p1 = 0, p2 = 0, index = 0; while (p1 < length1 && p2 < length2) { if (nums1[p1] < nums2[p2]) { helper[index++] = nums1[p1++]; } else { helper[index++] = nums2[p2++]; } } while (p1 < length1) { helper[index++] = nums1[p1++]; } while (p2 < length2) { helper[index++] = nums2[p2++]; } return helper; } }
運行結果如下:
代碼地址:https://github.com/professorxin/Java_Demo/blob/master/algorithm/src/MergeArrays.java