88. Merge Sorted Array
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]
維護三個 index,分別對應數組 A,數組 B青抛,和結果數組。然后 A 和 B 同時從后往前掃遵馆,每次迭代中 A 和 B 指向的元素大的便加入結果數組中,然后 index-1丰榴,另一個不動货邓。
public void merge(int A[], int m, int B[], int n) {
if(A==null || B==null)
return;
int idx1 = m-1;
int idx2 = n-1;
int len = m+n-1;
while(idx1>=0 && idx2>=0)
{
if(A[idx1]>B[idx2])
{
A[len--] = A[idx1--];
}
else
{
A[len--] = B[idx2--];
}
}
while(idx2>=0)
{
A[len--] = B[idx2--];
}
}