leetcode 341. Flatten Nested List Iterator
2016-06-01 23:36
183 查看
Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
Example 2:
Given the list
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
Subscribe to see which companies asked this question
很显然这个是一个递归问题,但是题目要求实现一个迭代器,这里我想到两个方法:
1. 直接在构造函数中使用递归构造好整个序列,然后逐个返回
2.栈保存历史记录,栈顶保存当前打印的列表以及打印到列表哪个位置,刚开始实现很顺利,但是后面提交发现测试用例有空列表的情况,如输入为[[],[[]]],这个
就麻烦了,该进后的方式就是保存一个缓存节点
下面是自己实现的方法:
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list
[[1,1],2,[1,1]],
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
[1,1,2,1,1].
Example 2:
Given the list
[1,[4,[6]]],
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
[1,4,6].
Subscribe to see which companies asked this question
很显然这个是一个递归问题,但是题目要求实现一个迭代器,这里我想到两个方法:
1. 直接在构造函数中使用递归构造好整个序列,然后逐个返回
2.栈保存历史记录,栈顶保存当前打印的列表以及打印到列表哪个位置,刚开始实现很顺利,但是后面提交发现测试用例有空列表的情况,如输入为[[],[[]]],这个
就麻烦了,该进后的方式就是保存一个缓存节点
下面是自己实现的方法:
#include <stack> #include <vector> #include <assert.h> struct NestedContext { const vector<NestedInteger>* vec; size_t pos; }; class NestedIterator { public: NestedIterator(vector<NestedInteger> &nestedList) { has_next = true; if (nestedList.empty()) { return; } NestedContext ctx = {&nestedList, 0}; s.push(ctx); } int next() { return cache_val; } bool _next(int& val) { while (!s.empty()) { NestedContext& ctx = s.top(); if (ctx.vec->at(ctx.pos).isInteger()) { int rv = ctx.vec->at(ctx.pos++).getInteger(); if (ctx.pos >= ctx.vec->size()) { s.pop(); } val = rv; return true; } else { const vector<NestedInteger>& nestedList = ctx.vec->at(ctx.pos++).getList(); if (ctx.pos >= ctx.vec->size()) { s.pop(); } if (!nestedList.empty()) { NestedContext new_ctx = {&nestedList, 0}; s.push(new_ctx); } } } return false; } bool hasNext() { has_next = _next(cache_val); return !s.empty() || has_next; } stack<NestedContext> s; bool has_next; int cache_val; };
相关文章推荐
- 9、策略模式
- CoordinatorLayout、AppBarLayout及控件扩展到状态栏
- 制作Aspose CHM文档的过程记录
- 项目中初试PHP单元测试
- 在虚拟机上配置linux永久ip的方法
- 【dp动态规划】飙车
- hdu5673(默慈金数、卡特兰数)
- [Android] Android使用序列化接口Parcelable、Serializable
- 关于SilverLight
- [置顶] 摊还分析 聚合法
- BZOJ 3224 Splay
- 关于SilverLight
- 【转】UIColor对颜色的自定义
- 映射器配置文件
- java类文件从编译到运行
- JavaScript提交form表单
- Ansible自动部署LNAMP
- 聊天实践
- JSP_JSP的9大内置对象
- Macbook OS X EI Capitan 10.11.5 WiFi不稳定