Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
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.
倒着插入,因为正着插入可能会导致A中的数据移动,倒着不会
Source
public void merge(int A[], int m, int B[], int n) {
int a = m - 1, b = n - 1, c = m + n - 1;
while( a >= 0 && b >= 0){
if(A[a] > B[b]){
A[c] = A[a];
c --;
a --;
}
else{
A[c] = B[b];
c --;
b --;
}
}
while(a >= 0){
A[c] = A[a];
c --;
a --;
}
while(b >= 0){
A[c] = B[b];
c --;
b --;
}
//System.out.println(Arrays.toString(A));
}
Test
public static void main(String[] args){
int[] A = {1,2,3,4,5,0,0}; //A数组开大一点,如果只开m的大小肯定会越界
int[] B = {4,6};
new Solution().merge(A,5,B,2); //传的时候没必要传开的那么大
}