【LeetCode 88 】 Merge Sorted Array
2015-09-05 20:00
274 查看
/* 题目: LeetCode 88 Merge Sorted Array 合并两个有序数组,使得合并后有序 Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. */ #include<iostream> using namespace std; // 假设aDst有足够的内存存储两个数组合并后的结果 void MergeSortedArray(int dst[], int src[], int dstLength , int srcLength) { int iSrc = srcLength - 1; int iDst = dstLength - 1; int iTarget = srcLength + dstLength - 1; while(iSrc >= 0 && iDst >= 0) { dst[iTarget--] = src[iSrc] > dst[iDst] ? src[iSrc--] : dst[iDst--]; } while(iSrc >= 0) { dst[iTarget--] = src[iSrc--]; } } int main() { int a[10] = {3,5, 6}; int b[4] = {2, 2, 4, 8}; for(int i = 0; i<10; i++) { cout << a[i] << ' '; } cout << endl; MergeSortedArray(a, b, 3, 4); for(int i = 0; i<10; i++) { cout << a[i] << ' '; } cout << endl; }
小结:
1)合并两个数组(包括字符串)时, 如果从前往后复制每个数字(或字符串)需要重复移动数字(或字符)多次, 那么我们可以考虑从后往前复制,这样就能减少移动的次数,从而提高效率;
2)这种反向思维很重要,往往由后往前更能得到优化的答案;
参考资料:
《剑指offer》 何海涛 老师
LeetCode
相关文章推荐
- 软件测试初体验
- 遍历DOM的所有节点,输出宽度高度都大于50的元素节点名称
- css样式表2
- Varnish
- 【数据库学习】机房收费系统(二)组合查询
- hdu5424 Rikka with Graph II
- druid配置(转)
- 【C++】各种成员变量
- HttpServletResponse编码问题
- DVWA之Brute Force
- SQL是写在程序里还是存储过程中好?
- 《C和指针》读书笔记
- PMP杂谈--进度数据,进度工具,进度方法,进度模型
- 关于引用和指针的区别
- 蓝懿iOS培训日志3 UI第一课及学习心得
- python 函数式编程工具
- java下radomAccessFile文件写入读取
- HDU1253 胜利大逃亡(DFS)
- 3.8 二叉树中结点最大的距离 & 重建二叉树 & 顺序遍历二叉树
- 黑马程序员之IO字符流及缓冲器