题目:
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
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
思路:
从最大的开始排,主要是严谨,多考虑边界的情况
Code:
public void merge(int A[], int m, int B[], int n) {
int len=m+n-1;
m--;n--;
while(len>=0){
if(m<0) {
A[len--]=B[n--];
continue;
}
if(n<0) {
A[len--]=A[m--];
continue;
}
if(A[m]>=B[n]) A[len--]=A[m--];
else A[len--]=B[n--];
}
}
备注:
生成的 array的长度是 m+n,所以 index 是 m+n-1