合并两个排序的整数数组A和B变成一个新的数组。
注意事项
你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。
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 len= m+n-1;
int lenA = m-1;
int lenB = n-1;
while(lenA>=0 && lenB>=0){
if(A[lenA]>B[lenB]){
A[len] = A[lenA];
lenA--;
len--;
}
else{
A[len] = B[lenB];
lenB--;
len--;
}
}
while(lenB>=0){//当B还有剩余时 A还有剩余无需移动
A[len]=B[lenB];
len--;
lenB--;
}
}
}
本文介绍了一种高效地将两个已排序的整数数组合并为一个新数组的方法。该方法利用了从数组尾部开始比较并放置较大元素的技巧,避免了传统方法中常见的元素移动操作,从而提升了算法效率。
763

被折叠的 条评论
为什么被折叠?



