Question: Merge two sorted arrays into one
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Idea: According to the solution in the offer, start from the end of the two arrays and add them in descending order until all array 2 is copied into array 1.
1 class Solution { 2 public void merge( int [] nums1, int m, int [] nums2, int n) { 3 m = m - 1 ;//m,n is now used as an index value 4 n = n - 1 ; 5 int i = m + n + 1 ; 6 while (m >= 0 || n >= 0 ){ 7 if (m < 0 ){//Indicates that nums1 has been compared, and the remaining value of nums2 is added to nums1 empty space in front. 8 nums1[i--] = nums2[n-- ]; 9 } else if (n < 0) {//Indicates that nums2 has been compared, and the previous ones of nums1 are already in order, so exit directly. 10 break; 11 } else { 12 nums1[i--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n-- ]; 13 } 14 } 15 } 16 }
Reference: https://segmentfault.com/a/1190000003707411