【题目描述】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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
两个有序的整型数组A和B,A数组长度为m,B数组长度为n,前提假设A有足够大的空间去容纳B。
【解题思路】分别给A和B两个指针i和j,当前指向A数组的指针指向的数值大于当前指向B数组的指针的情况下,让A整个数组往后移,将B指针指向的数值插入A中,然后指针往后移,由于插入一个数值去A数组中,要想数组下标依然指向之前得那个数值,必须也使i++;相反,就只让A数组指针往后移。还有一种情况必须考虑,如果A数组指针比B数组指针走得快些的话,就让B数组后面的值直接添加到A数组后面,否则就不做任何处理。
【考查内容】数组,排序
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int i = 0, j = 0, k,count;
while(j < n && i < m){
if(A[i] >= B[j]){
m++;
for(k = m-1; k > i; k--)
A[k] = A[k-1];
A[i] = B[j];
i++;
j++;
}
else
i++;
}
if(j < n){
while(j<n){
A[i] = B[j];
i++;
j++;
}
}
}
};