[leetcode] 281. Zigzag Iterator 解题报告
2016-03-13 23:12
351 查看
题目链接:https://leetcode.com/problems/zigzag-iterator/
Given two 1d vectors, implement an iterator to return their elements alternately.
For example, given two 1d vectors:
By calling next repeatedly until hasNext returns
the order of elements returned by next should be:
Follow up: What if you are given
well can your code be extended to such cases?
Clarification for the follow up question - Update (2015-09-18):
The "Zigzag" order is not clearly defined and is ambiguous for
does not look right to you, replace "Zigzag" with "Cyclic". For example, given the following input:
It should return
思路: 将两个一维数组中的数都先保存起来, 然后设置一个索引位来返回next, 如果已经到了尽头则返回false.
代码如下:
Given two 1d vectors, implement an iterator to return their elements alternately.
For example, given two 1d vectors:
v1 = [1, 2] v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returns
false,
the order of elements returned by next should be:
[1, 3, 2, 4, 5, 6].
Follow up: What if you are given
k1d vectors? How
well can your code be extended to such cases?
Clarification for the follow up question - Update (2015-09-18):
The "Zigzag" order is not clearly defined and is ambiguous for
k > 2cases. If "Zigzag"
does not look right to you, replace "Zigzag" with "Cyclic". For example, given the following input:
[1,2,3] [4,5,6,7] [8,9]
It should return
[1,4,8,2,5,9,3,6,7].
思路: 将两个一维数组中的数都先保存起来, 然后设置一个索引位来返回next, 如果已经到了尽头则返回false.
代码如下:
class ZigzagIterator { public: ZigzagIterator(vector<int>& v1, vector<int>& v2) { index = 0; hash.reserve(v1.size()+v2.size()); int k = 0; while(k < v1.size() || k < v2.size()) { if(k < v1.size()) hash.push_back(v1[k]); if(k < v2.size()) hash.push_back(v2[k]); k++; } } int next() { return hash[index++]; } bool hasNext() { return index < hash.size(); } private: int index; vector<int> hash; }; /** * Your ZigzagIterator object will be instantiated and called as such: * ZigzagIterator i(v1, v2); * while (i.hasNext()) cout << i.next(); */
相关文章推荐
- 嵌入式 uboot、fs、kernel制作和烧录简记-hi3518c
- Objective-C的基础语法总结
- Swift入门-Day 1
- spring基础-IO
- yum本地源的制作
- 闭关日记 Day01
- mysql (master/slave)复制原理及配置
- 主题模型及其变种的实现代码汇总
- Java day02 方法(交换数据,普通形式)
- React Native for android 项目驱动教程
- 一个三年Android开发的总结-开篇
- 数据库三大范式
- C语言——qsort排序
- uva10131 - Is Bigger Smarter?
- 产品文章理解之--成为产品经理必备的6种能力(引用)
- 使用RequestBuilder与服务器通讯
- 第三周
- java配置opencv-在eclipse中
- 编译openwrt记录
- 【原创】JDK动态代理,此次之后,永生难忘。