1. 具体题目
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明: 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例: 输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出: [1,2,2,3,5,6]
2. 思路分析
本题应该从数组尾部开始插入值,因为若从头部开始插值,nums1 数组中后面的元素都需要移动,代价太大。可知,nums2 中元素插入 nums1 中后,nums1 中最后有效元素的 index 为 n + m,所以从 nums1[n + m - 1] 出开始赋值,遍历两个数组中的元素,每次比较二者的值,将较大的一个插入到目标位置。
注意:若有一个数组先遍历完成,则将另一个数组中剩余元素填入 nums1 空余位置。
3. 代码
1 public void merge(int[] nums1, int m, int[] nums2, int n) {
2 int i = m - 1, j = n - 1;
3 int index = m + n - 1;
4 while(i >= 0 || j >= 0){
5 if(i < 0){
6 nums1[index] = nums2[j];
7 j--;
8 }else if(j < 0){
9 nums1[index] = nums1[i];
10 i--;
11 }else if(nums1[i] < nums2[j]){
12 nums1[index] = nums2[j];
13 j--;
14 }else{
15 nums1[index] = nums1[i];
16 i--;
17 }
18 index--;
19 }
20 }