Vison's Blog
所有文章
文章总览
编辑器
Publications
About Me
Search
目录
#toc-container
下载Markdown文件
【3.23】LeetCode每日一题· 扁平化嵌套列表迭代器
2021年03月23日 11时36分
标签:
LeetCode
dfs
树形结构
## 题目描述 给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。 #### 示例1 ``` 输入: [[1,1],2,[1,1]] 输出: [1,1,2,1,1] 解释: 通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,1,2,1,1]。 ``` #### 示例2 ``` 输入: [1,[4,[6]]] 输出: [1,4,6] 解释: 通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,4,6]。 ``` #### 来源 > 来源:力扣(LeetCode) > 链接:[题目链接](https://leetcode-cn.com/problems/flatten-nested-list-iterator/ "题目链接") ## 解题思路 这个数据结构和实现本博客**多级列表**的数据结构十分类似。一个列表中的所有**元素**代表同级的评论,而嵌套的子列表则表示某一子评论(回复)。可以将其转化为一棵树,其中叶子结点对应一个整数,非叶结点对应一个列表。 例如对于示例1 ``` [[1,1],2,[1,1]] ``` 对应的树为:  因此,我们可以使用**深度优先搜索**。当遍历到一个整数时,将其加入答案列表中;如果遍历到的是一个列表,则递归进入下一层遍历。 最后,遍历答案列表实现`next`和`hasNext`方法。 ### 代码 ```cpp /** * // 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
&getList() const; * }; */ class NestedIterator { private: vector
res; int pos; void dfs(vector
& nestedList){ for(NestedInteger& item: nestedList){ if(item.isInteger()){ res.emplace_back(item.getInteger()); }else{ dfs(item.getList()); } } } public: NestedIterator(vector
&nestedList) { dfs(nestedList); pos = 0; } int next() { return res[pos++]; } bool hasNext() { return pos < res.size(); } }; /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i(nestedList); * while (i.hasNext()) cout << i.next(); */ ``` ## 用时和内存 > 执行用时:4 ms,在所有 C++提交中击败了98.25%的用户 > 内存消耗:13.1 MB,在所有 C++提交中击败了66.87%的用户
所有评论
暂无评论
新增评论
评论
邮箱
邮箱仅作验证使用
图形验证码
邮箱验证码
发送验证码
发表评论
所有评论
暂无评论