- 题目
Given two sorted integer arrays A and B, merge B into A as one sorted array.
合并两个排序的整数数组A和B变成一个新的数组。 - 算法
如果单纯从前往后合并,那么效率会非常低,因为a数组后面的数字需要不停的移动。考虑从后往前比较,这样就不会产生需要数据后移的问题了。时间复杂度O(n+m)
public void mergeSortedArray(int[] a, int m, int[] b, int n) {
// write your code here
if (a == null || b == null) {
return;
}
int idx1 = m - 1;
int idx2 = n - 1;
int len = m + n - 1; //总共元素
while (idx1 >= 0 && idx2 >= 0) { //当两个数组中还有元素时
if (a[idx1] > b[idx2]) {
a[len--] = a[idx1--];
} else {
a[len--] = b[idx2--];
}
}
while (idx2 >= 0) { //当b中还有元素时,应为元素最后在a中,不用检测a
a[len--] = b[idx2--];
}
}
python
def mergeSortedArray(self, A, m, B, n):
# write your code here
for i in range(n):
A[i + m] = B[i]
A.sort()