Given two sorted integer arrays A and B, merge B into A as one sorted array.
** Notice
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
ExampleA = [1, 2, 3, empty, empty]
, B = [4, 5]
After merge, A will be filled as [1, 2, 3, 4, 5]
合并兩個排序好的數(shù)組杆勇,而且題目說明數(shù)組A的side大于m+n; 所以我們用的方法就是從兩個數(shù)組最后一個數(shù)字比起硕淑,大的就放到m+n-1的位置去妒牙,然后調(diào)整index之后繼續(xù)比下去直到一個數(shù)組先空為止暖途,在判斷把另一個有剩余的數(shù)組填進去辅肾。
class Solution {
/**
* @param A: sorted integer array A which has m elements,
* but size of A is m+n
* @param B: sorted integer array B which has n elements
* @return: void
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
// write your code here
int i = m-1, j = n-1, k = m+n-1;
while(i >= 0 && j >= 0){
if(A[i] < B[j]){
A[k] = B[j];
k--;
j--;
}else{
A[k] = A[i];
k--;
i--;
}
}
while(i >= 0){
A[k] = A[i];
k--;
i--;
}
while(j >= 0){
A[k] = B[j];
k--;
j--;
}
}
}