LC.88. Merge Sorted Array

https://leetcode.com/problems/merge-sorted-array/description/
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
The number of elements initialized in nums1 and nums2 are m and n respectively.


 1  /*
 2     * method 1: not good enough: used extra space!
 3     * time: o(m+n)
 4     * space: o(m+n): one calling stack but with extra space
 5     * 从前往后弄,需要额外空间
 6     * */
 7     public void merge(int[] nums1, int m, int[] nums2, int n) {
 8         int[] res = new int[m+n] ;
 9         int i = 0 ;
10         int j = 0 ;
11         int index = 0 ;
12         //first merge into the res and then copy to the nums1: o(m+n)
13         while(i<=m-1 && j<=n-1){
14             if (nums1[i]<=nums2[j]){
15                 res[index++] = nums1[i++] ;
16             } else{
17                 res[index++] = nums2[j++];
18             }
19         }
20         //one side left corner case: very common for two pointers
21         while(i<=m-1){
22             res[index++] = nums1[i++] ;
23         }
24         while(j<=n-1){
25             res[index++] = nums2[j++];
26         }
27         //copy from res to nums1
28         for (int k = 0; k < res.length; k++) {
29             nums1[k] = res[k];
30         }
31     }
32 
33     /* time(m+n) space: o(1)
34     * nums1{3,4,5, , }
35     * nums2{1,2}
36     * 从后往前弄就不需要额外的空间了, 很巧妙
37     * */
38     public void merge2(int[] nums1, int m, int[] nums2, int n){
39         int i = m-1 ;
40         int j = n -1 ;
41         int k = m+n-1;
42         while(i>=0 && j>=0){
43             nums1[k--] = nums1[i]>=nums2[j]? nums1[i--] : nums2[j--] ;
44         }
45         // {3,4,3,4,5} 这种情况,I 已经到最左边了 需要把J 复写在上面
46         while(i>=0){
47             nums1[k--] = nums1[i--];
48         }
49         while(j>=0){
50             nums1[k--] = nums2[j--] ;
51         }
52     }
原文地址:https://www.cnblogs.com/davidnyc/p/8553334.html