剑指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
- 剑指Offer----面试题四之相关题目
- 剑指offer面试题java实现之题4之相关题目:两个排序数组合并
- 剑指offer面试题java实现之题7之相关题目:用两个队列实现一个栈
- 《剑指Offer》面试题四之替换空格
- 剑指offer 面试题题目汇总
- 剑指offer面试题4扩展题目
- 剑指Offer----面试题四:替换空格
- 剑指offer,面试题四替换空格
- 剑指offer面试题04后面小题目
- 《剑指Offer》面试题3及LeetCode中相似题目
- 剑指offer面试题之替换空格
- 剑指offer面试题之跳台阶
- 剑指offer面试题之扑克牌顺子
- 剑指offer 面试题
- 剑指offer面试题
- 面试题之四
- 面试题之四
- 剑指offer面试题4:替换空格 相关题目 排序的数组A2中所有数字插入到A1并保持排序
- iOS信号量-dispatch_semaphore
- [Network Analysis] 复杂网络分析总结
- 用户名与密码
- js 从一个select选择数据添加到另一个select(包括移除)
- 等差数列
- 剑指Offer----面试题四之相关题目
- 测试
- LeenCode--Remove Element
- 笔试题60. LeetCode OJ (47)
- 信号与系统相关网站
- Androidstudio安装GsonFormat快速生成实体类插件
- 2016520
- 创业公司如何实施敏捷开发
- ImageView组图动画轮播