Flatten Nested List Iterator问题及解法
2017-09-21 09:53
357 查看
问题描述:
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.
示例:
Given the list
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
Given the list
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
问题分析:
将nestedlist中的值倒序存在stack中,对stack的首元素进行分析,若为整数,则可以输出,若还是nestedlist,重复前面的操作。
过程详见代码:
class NestedIterator {
pu
9d98
blic:
stack<NestedInteger> s;
NestedIterator(vector<NestedInteger>& nestedList) {
for (int i = nestedList.size() - 1; i >= 0; i--)
{
s.push(nestedList[i]);
}
}
int next() {
int res = s.top().getInteger();
s.pop();
return res;
}
bool hasNext() {
while (!s.empty())
{
NestedInteger t = s.top();
if (t.isInteger()) return true;
s.pop();
vector<NestedInteger>& adjs = t.getList();
for (int i = adjs.size() - 1; i >= 0; i--)
{
s.push(adjs[i]);
}
}
return false;
}
};
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.
示例:
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].
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].
问题分析:
将nestedlist中的值倒序存在stack中,对stack的首元素进行分析,若为整数,则可以输出,若还是nestedlist,重复前面的操作。
过程详见代码:
class NestedIterator {
pu
9d98
blic:
stack<NestedInteger> s;
NestedIterator(vector<NestedInteger>& nestedList) {
for (int i = nestedList.size() - 1; i >= 0; i--)
{
s.push(nestedList[i]);
}
}
int next() {
int res = s.top().getInteger();
s.pop();
return res;
}
bool hasNext() {
while (!s.empty())
{
NestedInteger t = s.top();
if (t.isInteger()) return true;
s.pop();
vector<NestedInteger>& adjs = t.getList();
for (int i = adjs.size() - 1; i >= 0; i--)
{
s.push(adjs[i]);
}
}
return false;
}
};
相关文章推荐
- 341. Flatten Nested List Iterator
- 341. Flatten Nested List Iterator
- Flatten Binary Tree to Linked List问题及解法
- 341. Flatten Nested List Iterator
- 寻找必败态——一类博弈问题的快速解法
- Increasing Triplet Subsequence问题及解法
- Longest Word in Dictionary through Deleting问题及解法
- Next Permutation问题及解法
- Ones and Zeroes 问题及解法
- 简单的汉诺塔问题解法代码
- 矩阵连乘问题的非动态解法
- 百鸡百钱问题C++解法
- Remove Duplicates from Sorted List II问题及解法
- Binary Tree Right Side View问题及解法
- TXT格式的Excel表格读取问题优化解法(目前我所知的最简洁算法)
- 约瑟夫环问题的简单解法(数学公式法)
- Convert BST to Greater Tree问题及解法
- 【经典算法】:开灯问题,貌似没啥新解法了。。。
- VC++程序启动画面会先看到MainFrame先闪一下再消失的问题解法
- Android开发自定义ListView解决在NestedScrollView里不能用listview的问题(ScrollView嵌套ListView的问题)