题目地址:https://leetcode.com/problems/flatten-nested-list-iterator/description/

题目描述

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 [[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].

题目大意

生成一个嵌套的数组迭代对象的迭代器。

解题方法

递归+队列

该做法是作弊方法,因为题目想要我们给出的迭代器应该是对原始对象的迭代,而不是对自己新建对象的迭代。

这个做法需要我们设计一个数据结构保存嵌套数组的每个元素,我们选择了队列。

重点是利用递归把整个嵌套的列表迭代器给压平。注意,题目已经给了我们它的数据结构,而不是普通的list。所以我们必须用他的函数。题目中虽然是多重嵌套,但是归根到底,对于每层的嵌套都是一个一维数组而已。因此,不要想复杂,直接循环该一维数组,如果是整数,添加到队列中,如果是嵌套的列表则继续解嵌套。

最后的结果是有按照从左到右有序的,这个可以放心。

Python代码如下:

# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """ class NestedIterator(object): def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.queue = collections.deque()
def getAll(nests):
for nest in nests:
if nest.isInteger():
self.queue.append(nest.getInteger())
else:
getAll(nest.getList())
getAll(nestedList) def next(self):
"""
:rtype: int
"""
return self.queue.popleft() def hasNext(self):
"""
:rtype: bool
"""
return len(self.queue) # Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

上面说了事先保存所有对象的方法是个作弊的方法,为了不事先保存所有的对象,而是每次在调用hasNext()或者next()时迭代器向后移动,我们可以使用栈。用到栈的想法出发点是递归本身是用栈实现的。

栈存储的是NestedInteger类型,这样把vector中的元素倒序放进来,在hasNext()的判断过程中,如果看到当前的元素是Integer数据那么直接弹出;如果看到的是List类型,那么应该对其进行for循环,把里面的Integer再倒序放进来。

C++代码如下:

/**
* // 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:
NestedIterator(vector<NestedInteger> &nestedList) {
for (int i = nestedList.size() - 1; i >= 0; --i) {
st.push(nestedList[i]);
}
} int next() {
NestedInteger cur = st.top(); st.pop();
return cur.getInteger();
} bool hasNext() {
while (!st.empty()) {
NestedInteger cur = st.top();
if (cur.isInteger()) {
return true;
}
st.pop();
for (int i = cur.getList().size() - 1; i >= 0; --i) {
st.push(cur.getList()[i]);
}
}
return false;
}
private:
stack<NestedInteger> st;
}; /**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/

日期

2018 年 3 月 12 日
2019 年 10 月 2 日 —— 欢度国庆

【LeetCode】341. Flatten Nested List Iterator 解题报告(Python&C++)的更多相关文章

  1. [LeetCode] 341. Flatten Nested List Iterator 压平嵌套链表迭代器

    Given a nested list of integers, implement an iterator to flatten it. Each element is either an inte ...

  2. [leetcode]341. Flatten Nested List Iterator展开嵌套列表的迭代器

    Given a nested list of integers, implement an iterator to flatten it. Each element is either an inte ...

  3. LeetCode 341. Flatten Nested List Iterator

    https://leetcode.com/problems/flatten-nested-list-iterator/

  4. 【leetcode】341. Flatten Nested List Iterator

    题目如下: Given a nested list of integers, implement an iterator to flatten it. Each element is either a ...

  5. 341. Flatten Nested List Iterator展开多层数组

    [抄题]: Given a nested list of integers, implement an iterator to flatten it. Each element is either a ...

  6. 341. Flatten Nested List Iterator

    List里可以有int或者List,然后里面的List里面可以再有List. 用Stack来做比较直观 Iterator无非是next()或者hasNext()这2个方程 一开始我想的是hasNext ...

  7. 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...

  8. 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

  9. 【LeetCode】784. Letter Case Permutation 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 循环 日期 题目地址:https://leet ...

随机推荐

  1. gcc 引用math 库 编译的问题 解决方法

    1.gcc app.c -lm 其中lm表示的是连接 m forlibm.so / libm.a表示你想要的库 abc for libabc.so / libabc.a 其中.a表示的是静态链接库 . ...

  2. POLLOUT/POLLINT事件触发测试

    一般poll使用过程中都是检测POLLIN事件,表示描述符有事件可以处理了,需要我们处理.对POLLOUT事件触发的方式相对较少,网上也有很多对此触发的疑问,利用实际项目中用的一个用法,下面做了个测试 ...

  3. BIO/NIO/AIO对比

    IO 模型 就是使用什么样的通道进行数据的发送和接收,很大程度上决定了程序通信的性能. Java 支持三种网络编程模型:BIO.NIO.AIO. Java BIO,同步并阻塞(传统阻塞型),服务器实现 ...

  4. day34 前端基础之JavaScript

    day34 前端基础之JavaScript ECMAScript 6 尽管 ECMAScript 是一个重要的标准,但它并不是 JavaScript 唯一的部分,当然,也不是唯一被标准化的部分.实际上 ...

  5. Spring同一个类中的注解方法调用AOP失效问题总结

    public interface XxxService { // a -> b void a(); void b(); } @Slf4j public class XxxServiceImpl ...

  6. Java中特殊的类——Object类

    Java中特殊的类--Object类 1.Object类的概述 Object类是java默认提供的类.Java中除了Object类,所有的类都是有继承关系的.默认会继承Object类,即所有的对象都可 ...

  7. navicat突然连接不上远程linux服务器上的mysql

    我linux服务器上的mysql是docker安装的,突然有一天我的navicat连接不上服务器上的mysql,于是开始了下面一系列的修复 1.首先登录服务器上mysql,看是否能正常登录,我发现不能 ...

  8. Windows下80端口被占用的解决方法(SQL Server)

    查找80端口被谁占用的方法 进入命令提示行(WIN+R 输入 CMD),输入命令 netstat -ano|findstr 80 (显示包含:80的网络连接) ,就可以看到本机所有端口的使用情况,一般 ...

  9. springmvc中如何自定义类型转换器

    package com.hope.utils;import org.springframework.core.convert.converter.Converter;import org.spring ...

  10. 通过SSE(Server-Send Event)实现服务器主动向浏览器端推送消息

    一.SSE介绍 1.EventSource 对象 SSE 的客户端 API 部署在EventSource对象上.下面的代码可以检测浏览器是否支持 SSE. if ('EventSource' in w ...