Title description
Given two ordered arrays of integers A and B, please merge array B into array A to become an ordered array.
Note:
You can assume that array A has enough space to store the elements of array B, A and B The initial number of elements are m and n
public class Solution {
public void merge(int A[], int m, int B[], int n) {
//数组A中初始化好的index长度
int aInitIndex = m - 1;
//数组B中初始化好的index长度
int bInitIndex = n - 1;
//数组A B加一起的元素个数总长度的index
int abIndex = m + n -1;
//m >= n 即 aIndex >= bIndex的情况
while(aInitIndex>=0 && bInitIndex>=0){
if(A[aInitIndex] > B[bInitIndex]){
//从A、B的数组末尾开始计算比较 当:数组A中的元素 > 数组B中的元素
A[abIndex--] = A[aInitIndex--];
}else{
A[abIndex--] = B[bInitIndex--];
}
}
//m < n 即 aIndex < bIndex的情况
while(bInitIndex>=0){
A[abIndex--] = B[bInitIndex--];
}
}
}