[LeetCode] [Java] Merge Sorted Array
Question:
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 nums1and nums2 are m and n respectively.
Question:
Given two ordered arrays nums1 and nums2, combine the two arrays into an ordered array.
Note:
You can assume that nums1 has enough space (greater than or equal to m + n) to include additional elements from nums2. The numbers of starting elements in nums1and nums2 are m and n.
Algorithm analysis:
Method 1:
The first time AC did not consider too much space complexity, it opened up a new array to contain the merging elements in num1 and nums2, and then overwritten nums1with this new array.
Use two pointers to traverse nums1 and nums2 respectively, and compare the large elements into the new array.
Method 2:
Maintain A pointer for each array, and then compare the value pointed by the pointer. In each iteration, the elements A and B point to are added to the result array, and then index-1, the other does not move. This is because the result of this question is still in A. If you scan it before, it is possible to overwrite the unchecked elements.
AC code:
Method 1:
Public class Solution {public void merge (int [] nums1, int m, int [] nums2, int n) {if (n = 0) return; if (m = 0) {for (int I = 0; I
Method 2:
public class Solution { public void merge(int A[], int m, int B[], int n) { while(m > 0 && n > 0) { if(A[m-1] > B[n-1]) { A[m+n-1] = A[m-1]; m--; } else { A[m+n-1] = B[n-1]; n--; } } while(n > 0){ A[m+n-1] = B[n-1]; n--; } }}