题目描述1:有两个排序的数组A1和A2,内存在A1的末尾有足够多的空余空间容纳A2。请实现一个函数,把A2中的所有数字插入A1中,并且所有的数字是排序的。
void MergeList(int La[],int a_length,int Lb[],int b_length){
cout << "MergeList" << endl;
if (a_length <= 0 && b_length <= 0){
cout << "there exists a null array" << endl;
return;
}
for (int i = 0; i < a_length-1; i++){
if (La[i] > La[i + 1]){
cout << "La is not the right array" << endl;
return;
}
}
for (int i = 0; i < b_length - 1; i++){
if (Lb[i] > Lb[i + 1]){
cout << "Lb is not the right array" << endl;
return;
}
}
int m_length = a_length + b_length;
int a_index = a_length - 1;
int b_index = b_length - 1;
int m_index = m_length - 1;
while (a_index >= 0 &&b_index >= 0){
if (La[a_index] <= Lb[b_index]){
La[m_index] = Lb[b_index];
b_index--;
}
else{
La[m_index] = La[a_index];
a_index--;
}
m_index--;
}
while (a_index >= 0){
La[m_index--] = La[a_index--];
}
while (b_index >= 0){
La[m_index--] = Lb[b_index--];
}
//return La;
}
时间复杂度:O(a_length + b_length)
空间复杂度:O(1)
参考链接:
《剑指offer》 P55 相关题目
题目描述2:有两个排序的数组A1和A2,请实现一个函数,把A1、A2中的所有数字插入新的数组A3中,并且所有的数字是排序的。
void MergeListNew(int La[],int a_length,int Lb[],int b_length,int Lc[],int c_length){
cout << "MergeListNew Start" << endl;
if (a_length <= 0 && b_length <= 0){
cout << "there exists a null array" << endl;
return;
}
for (int i = 0; i < a_length - 1; i++){
if (La[i] > La[i + 1]){
cout << "La is not the right array" << endl;
return;
}
}
for (int i = 0; i < b_length - 1; i++){
if (Lb[i] > Lb[i + 1]){
cout << "Lb is not the right array" << endl;
return;
}
}
int a_index = 0;
int b_index = 0;
int c_index = 0;
while (a_index < a_length && b_index < b_length){
if (La[a_index] <= Lb[b_index]){
Lc[c_index] = La[a_index];
a_index++;
}
else{
Lc[c_index] = Lb[b_index];
b_index++;
}
c_index++;
}
while (a_index < a_length){
Lc[c_index] = La[a_index];
a_index++;
c_index++;
}
while (b_index < b_length){
Lc[c_index] = Lb[b_index];
b_index++;
c_index++;
}
}
时间复杂度:O(a_length + b_length)
空间复杂度:O(a_length + b_length)
参考链接:
《数据结构》严蔚敏 吴伟民编著 P20 例2-2
相关project链接:
https://github.com/nihaizai/-offer/tree/master/%E5%90%88%E5%B9%B6%E6%95%B0%E7%BB%84