[LC] 88 title Merge Sorted Array (merging two ordered arrays)

① English title

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.
Example:

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

Output: [1,2,2,3,5,6]

② Chinese Title:

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: this problem, reverse the order of better than doing something. A well thought, with three variable index, i, j, k pointing num1 the last one, the last bit of the array after the last bit nums2 mixed. After completion of each process, it should be lower and subtract 1. But to pay attention only to participate in the index will move down and subtract 1.

              While loop, i and j are greater than or equal to 0 condition. Two array elements compared to those who took big assigned to the last one who mixed array.

              Further, when the i has been decremented to a negative number and j is a further positive (that is longer than the array length nums2 nums1 s), assigned directly to the remaining not go nums2 value, assigned to the previous eleven mixed array bit.

             Because I just put nums1 as the array after mixing, so when j i decrement is negative or positive and when, without any treatment, and that is my code in the 17-21 row can be deleted ( I have to write code to facilitate, for example child).

④ Code:

  

 1 class Solution {
 2     public void merge(int[] nums1, int m, int[] nums2, int n) {
 3         int i=m-1;
 4         int j=n-1;
 5         int k=m+n-1;
 6         while(i>=0 && j>=0){
 7           if(nums1[i]>=nums2[j])
 8                 nums1[k--]=nums1[i--];
 9           else                 
10                 nums1[k--]=nums2[j--];
11         }
12         if( j>=0 ){
13             for(int p=0 ; p<j+1; p++){
14                 nums1[p] = nums2[p];
15             }  
16          }
17        // if( i>0  ){
18         //    for(int p=0 ; p<i+1;p++){
19         //    nums1[p]= nums1[p];
20         //    }  
21          //}
22     }
23 }

 

Guess you like

Origin www.cnblogs.com/zf007/p/11520760.html