LintCode 6 合并排序数组
来源:互联网 发布:淘宝买奢侈品 编辑:程序博客网 时间:2024/06/05 07:28
题目:mergeSortedArray
要求:
合并两个排序的整数数组A和B变成一个新的数组。
样例:
给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
算法要求:
你能否优化你的算法,如果其中一个数组很大而另一个数组很小?
解题思路:
使用迭代器遍历2个数组,如果A的迭代器比B中的小,则存入第三个数组,并将A的迭代器迭代一次,否则将B的迭代器存入第三个数组,并将迭代器迭代一次(这里的迭代器可以理解成指针或者游标)。如果某个迭代器先迭代完成,则只需要将剩下的都存入到第三个数组中即可。
算法如下:
vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) { vector<int>::iterator itA = A.begin(); vector<int>::iterator itB = B.begin(); vector<int> C; while (itA != A.end() && itB != B.end()) { if(*itA < *itB) { C.push_back(*itA); itA++; } else { C.push_back(*itB); itB++; } } while(itA != A.end()) { C.push_back(*itA); itA++; } while(itB != B.end()) { C.push_back(*itB); itB++; } return C; }
0 0
- LintCode 6 合并排序数组
- LintCode 合并排序数组
- LintCode: 合并排序数组
- lintcode ----合并排序数组
- LintCode:合并排序数组
- lintcode--合并排序数组
- Lintcode合并排序数组
- Lintcode:合并排序数组
- (lintcode)第6题 合并排序数组
- LintCode之6 合并排序数组
- LintCode 合并排序数组 II
- 合并排序数组(LintCode)
- LintCode(easy)合并排序数组
- LintCode-合并排序数组 II
- 【lintcode笔记】合并排序数组
- Lintcode 合并排序数组 II
- LintCode-合并排序数组 II
- 【LintCode】合并排序数组 II
- matlab根据行列索引矩阵寻找元素
- 简单图片库
- js完美运动框架最终版
- ionic2 数据更新,刷新页面
- 菜鸟java
- LintCode 6 合并排序数组
- 移植三星版本uboot_s5pv210
- shell命令之基本的数组操作
- Codeforces Round #367 (Div. 2) E. Working routine(十字链表)
- LaTeX/Tables
- C# .net中cookie值为中文时的乱码解决方法
- 01_考虑用静态工厂方法代替构造器
- GPIO八种工作模式总结
- 【React-Router】关于browserHistory出现did not match any routes的问题