力扣 341. 扁平化嵌套列表迭代器 递归/栈/python 生成器
发布日期:2021-11-05 06:59:29 浏览次数:15 分类:技术文章

本文共 5023 字,大约阅读时间需要 16 分钟。

在这里插入图片描述

思路一:最简单的思路,采用递归直接预处理出一个数组来存储结果,那么这两个函数就很好写了。但是我感觉这样的设计并不能算是迭代器。

/** * // 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 {
public: NestedIterator(vector
&nestedList) {
dfs(nestedList); pos=0; siz=vec.size(); } int next() {
return vec[pos++]; } bool hasNext() {
return pos
vec; int pos,siz; void dfs(vector
&nestedList){
for(auto node:nestedList){
if(node.isInteger()) vec.push_back(node.getInteger()); else dfs(node.getList()); } }};/** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i(nestedList); * while (i.hasNext()) cout << i.next(); */

思路二:利用栈。我们搞一个 s t a c k stack stack存储 N e s t e d I n t e g e r NestedInteger NestedInteger,并且保证要么栈为空,要么栈顶的元素一定是一个数。现在考虑怎么在栈中存放数据,当我们面对一个 v e c t o r < N e s t e d I n t e g e r > vector<NestedInteger> vector<NestedInteger>时,递归的做法是从第一个元素依次往后处理,如果某个元素不是数字,则需要再次递归下去;用栈怎么搞呢呢?我们可以从最后一个元素开始,把他们依次放到栈中,那么栈顶元素就是第一个元素,如果此时栈顶元素不是数字,那么就需要把它弹出,得到它的 L i s t List List并继续这个过程。

/** * // 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 {
public: NestedIterator(vector
&nestedList) {
initstack(nestedList); } int next() {
int val=s.top().getInteger(); s.pop(); return val; } bool hasNext() {
//栈非空 且栈顶元素不是数字 while(!s.empty()&&!s.top().isInteger()){
NestedInteger tmp=s.top(); s.pop(); initstack(tmp.getList()); } return !s.empty(); }private: stack
s; void initstack(vector
&nestedList){
int siz=nestedList.size(); //倒着放进去 for(int i=siz-1;i>=0;i--) s.push(nestedList[i]); }};/** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i(nestedList); * while (i.hasNext()) cout << i.next(); */

思路三:利用python的生成器。

# """# This is the interface that allows for creating nested lists.# You should not implement it, or speculate about its implementation# """#class NestedInteger:#    def isInteger(self) -> bool:#        """#        @return True if this NestedInteger holds a single integer, rather than a nested list.#        """##    def getInteger(self) -> int:#        """#        @return the single integer that this NestedInteger holds, if it holds a single integer#        Return None if this NestedInteger holds a nested list#        """##    def getList(self) -> [NestedInteger]:#        """#        @return the nested list that this NestedInteger holds, if it holds a nested list#        Return None if this NestedInteger holds a single integer#        """class NestedIterator:    def __init__(self, nestedList: [NestedInteger]):                def gen(nestedList):            for each in nestedList:                if each.isInteger():                    yield each.getInteger()                else:                    yield from gen(each.getList())                self.iterator=gen(nestedList)        try:            self.value=next(self.iterator)        except StopIteration:            self.value=None    def next(self) -> int:        ans=self.value        try:            self.value=next(self.iterator)        except StopIteration:            self.value=None        return ans        def hasNext(self) -> bool:        return self.value!=None         # Your NestedIterator object will be instantiated and called as such:# i, v = NestedIterator(nestedList), []# while i.hasNext(): v.append(i.next())

转载地址:https://blog.csdn.net/xiji333/article/details/107952263 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:力扣 1130. 叶值的最小代价生成树 区间dp/单调栈
下一篇:力扣 面试题 17.21. 直方图的水量 dp/双指针/单调栈

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月18日 11时33分05秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章