A. Merge Sorted Array
Given sorted integer Arrays nums1 and nums2, merge nums2 into nums1 as one sorted Array.
Note:
Assume that nums1 have enough space (size that's greater or equal to m + n) to hold add Itional elements from nums2. The number of elements initialized in nums1 and nums2 is m and n respectively.
Topic:
Given two sorted integer arrays A and B, merge B into a sorted array.
Note: You can assume that a has enough space (greater than or equal to M + N) to hold additional elements from B.
Analysis:
Loop recursive solution, the largest in the final, reverse processing
Method 1:
1 Public classSolution {2 Public voidMergeint[] nums1,intMint[] Nums2,intN) {3 //especially note that the m here is only the number of elements in the NUMS1, not the length of the final first array do not use m=nums1.length, otherwise it will cause data to cross the error4 5 intI=m-1,j=n-1,index=m+n-1;6 7 while(i>=0&&j>=0){8 if(nums1[i]>Nums2[j]) {9 //a large will put an array of a further behindTennums1[index--]=nums1[i--]; One A } - Else{ -nums1[index--]=nums2[j--]; the - } - } - while(i>=0){ + //a large will put an array of a further behind -nums1[index--]=nums1[i--]; + } A while(j>=0){ atnums1[index--]=nums2[j--]; - } - - } -}
Method 2:3 lines of code
Public class Solution { publicvoid merge (intint. int int N) { int i=m-1, j=n-1, k=m+n-1; while (I>-1 && j>-1) A[k--]= (A[i]>b[j])? a[i--]: b[j--]; while (j>-1) a[k--]=b[j--];} }
The merge Sorted array "Leetcode" algorithm, in which Java merges two ordered arrays into an array