题目:
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.
说明:无
实现:
精简实现:
// 时间复杂度 O(m+n),空间复杂度 O(1)
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int i=m-,j=n-,k=m+n-;
while(i>=&&j>=)//从后面开始比较归并,直到有一个数组归并完
{
A[k--]=A[i]>B[j]?A[i--]:B[j--];//将大数赋给A[k]
}
while(j>=)//若B还没归并完,直接归并到A
A[k--]=B[j--];
}
};