# [LeetCode] 88. 合并两个有序数组

## Description

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3



## Analyse

### 归并排序(Merge sort)

class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
// 先将 nums2 append 到 nums1
// public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
System.arraycopy(nums2, 0, nums1, nums1.length - nums2.length, nums2.length);
int low = 0, high = nums1.length - 1;

// merge sort
mergeSort(nums1, low, high);
}

// 将数组拆分成两部分，直到有序
private void mergeSort(int[] nums, int low, int high) {
// base case
if (low >= high) return;

int mid = low + (high - low) / 2; // 不用(low + high) / 2 防止加法溢出

mergeSort(nums, low, mid);
mergeSort(nums, mid+1, high);

merge(nums, low, mid, high);
}

// 合并两个有序数组（或数据的两个有序部分）
private void merge(int [] nums, int low, int mid, int high) {
// 双指针法
int p = low, q = mid + 1;

// 需要一个临时空间
int[] tmpNums = new int[high - low + 1];
int index = 0;
while (p <= mid && q <= high) {
if (nums[p] < nums[q]) {
tmpNums[index++] = nums[p++];
} else {
tmpNums[index++] = nums[q++];
}
}

while (p <= mid) {
tmpNums[index++] = nums[p++];
}

while (q <= high) {
tmpNums[index++] = nums[q++];
}

// 将排好序的值写回nums
System.arraycopy(tmpNums, 0, nums, low, high - low + 1);
}
}


public void merge(int[] nums1, int m, int[] nums2, int n) {
// 先将 nums2 append 到 nums1
System.arraycopy(nums2, 0, nums1, m, n);

// int low = 0, high = m - 1;

// merge sort
// mergeSort(nums1, low, high);
merge(nums1, 0, m - 1, m + n - 1);
}

posted @ 2020-07-01 11:25  arcsinW  阅读(202)  评论(0编辑  收藏  举报