剑指Offer----面试题四之相关题目

来源:互联网 发布:手机sql注入工具 编辑:程序博客网 时间:2024/06/05 19:10

转载请注明出处<http://blog.csdn.net/qianqin_2014/article/details/51455913>


题目:

有两个排序的数组A1和A2,内存在A1的末尾有足够多的空余空间容纳A2。请实现一个函数,把A2中所有的数字插入到A1中并且所有的数字是排序的。

思路一:

不管三七二十一,先插入,再排序。

思路二:

根据面试题四的思路,从后向前依次插入。

源代码:

#include<iostream>//参数分别代表:数组A,数组A中元素的个数,数组A的长度,数组B,数组B中元素的个数void Add(int *A, int lenA, int len,  int *B, int lenB){if (len < lenA + lenB)return;int indexInsert = lenA + lenB - 1;int indexA = lenA - 1;int indexB = lenB - 1;for (int i = 0; i < lenB; i++){if (B[indexB] > A[indexA])A[indexInsert--] = B[indexB--];else if (B[indexB] == A[indexA]){A[indexInsert--] = B[indexB--];A[indexInsert--] = A[indexA--];}else{A[indexInsert--] = A[indexA--];}}if (indexB == (lenB-1)){for (int i = 0; i < lenB; i++)A[i] = B[i];}}void test1(){std::cout << "==========test1=========" << std::endl;int A[10] = { 5, 6, 7, 8 };int B1[] = { 1, 2, 3, 4 };Add(A, 4, 10, B1, 4);for (int i = 0; i < 8; i++)std::cout << A[i] << "  ";std::cout << std::endl;}void test2(){std::cout << "==========test2=========" << std::endl;int A[10] = { 5, 6, 7, 8 };int B2[] = { 9, 10, 11, 12 };Add(A, 4, 10, B2, 4);for (int i = 0; i < 8; i++)std::cout << A[i] << "  ";std::cout << std::endl;}void test3(){std::cout << "==========test3=========" << std::endl;int A[10] = { 5, 6, 7, 8 };int B3[] = { 7, 8, 9, 10 };Add(A, 4, 10, B3, 4);for (int i = 0; i < 8; i++)std::cout << A[i] << "  ";std::cout << std::endl;}int main(){test1();test2();test3();system("pause");return 0;}

运行结果:

==========test1=========1  2  3  4  5  6  7  8==========test2=========5  6  7  8  9  10  11  12==========test3=========5  6  7  7  8  8  9  10请按任意键继续. . .


转载请注明出处<http://blog.csdn.net/qianqin_2014/article/details/51455913>


0 0