1、描述
给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。
列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。
示例 1:
输入: [[1,1],2,[1,1]]
输出: [1,1,2,1,1]
解释: 通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,1,2,1,1]。
来源:力扣(LeetCode)
链接
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2、关键字
列表,嵌套,多层,有数有列表,迭代器使用,遍历,
3、思路
多叉树的先序遍历(深度优先遍历),列表就是中间节点,数字就是叶子节点,常规数字遍历:使用栈从右边往左边使孩子进栈,
这次使用递归dfs
4、notes
题目给出一个类,然后给出判断列表的操作,可以判断出来下一个元素是列表,还是数字,本身提供了方法。
使用dfs递归调用,把这个函数分出来写,
初始化一个数字vector,和数字的迭代器,在遍历的时候填充,然后再实现给出的两个函数,判空和输出,
5、复杂度
时间:初始化为O( N),n是数字个数,取数据和判空是O(1);
空间:O(N),数组长度,
6、code
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class NestedIterator {
public:
vector<int>:: iterator cur;
vector<int> num;
void dfs (vector<NestedInteger> &nestedList){
for (auto & tem : nestedList){
if(tem.isInteger()){
num.push_back(tem.getInteger());
}
else {
dfs(tem.getList());
}
}
}
NestedIterator(vector<NestedInteger> &nestedList) {
dfs(nestedList);
cur = num.begin();
}
int next() {
return *cur ++;
}
bool hasNext() {
return cur!=num.end();
}
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/