Given two ordered arrays of integers and nums2 nums1, incorporated into the nums2 nums1 in an ordered array such as a num1.
Description:
And initializing the number of elements nums1 nums2 of m and n.
You can assume nums1 sufficient space (space equal to or greater than m + n) to save the elements of nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m =. 3
nums2 = [2,5,6], n-=. 3
Output: [1,2,2,3,5,6]
Thinking
Directly to the largest, from the back to put elements traversed once completed
. 1 class Solution { 2 public : . 3 void Merge (Vector < int > & nums1, int m, Vector < int > & nums2, int n-) { . 4 // directly to the largest . 5 for ( int I = m + N- . 1 , i_1 = M- . 1 , = N- i_2 are used . 1 ; I> = 0 ; i-- ) { . 6 // nums1 empty array, i = n-1, i_1 = 0-1 = -1, i_2 = n-1 . 7 IF (i_1 < 0 ) { . 8 nums1 [I] = nums2 [i_2 are used]; . 9 i_2--;//同nums1[i]=nums2[i_2--]; 10 continue; 11 } 12 //nums2空数组, n=0, i=m-1, i_1=m-1, i_2=0-1=-1 13 if(i_2<0){ 14 nums1[i] = nums1[i_1]; 15 i_1--; 16 continue; 17 } 18 if(nums1[i_1] >= nums2[i_2]){ 19 nums1[i]=nums1[i_1]; 20 i_1--; 21 } 22 else { 23 nums1 [i] = nums2 [I_2]; 24 i_2-- ; 25 } 26 27 } 28 } 29 };