【LeetCode】341. Flatten Nested List Iterator 解题报告(Python&C++)
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
题目地址: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++)的更多相关文章
- [LeetCode] 341. Flatten Nested List Iterator 压平嵌套链表迭代器
Given a nested list of integers, implement an iterator to flatten it. Each element is either an inte ...
- [leetcode]341. Flatten Nested List Iterator展开嵌套列表的迭代器
Given a nested list of integers, implement an iterator to flatten it. Each element is either an inte ...
- LeetCode 341. Flatten Nested List Iterator
https://leetcode.com/problems/flatten-nested-list-iterator/
- 【leetcode】341. Flatten Nested List Iterator
题目如下: Given a nested list of integers, implement an iterator to flatten it. Each element is either a ...
- 341. Flatten Nested List Iterator展开多层数组
[抄题]: Given a nested list of integers, implement an iterator to flatten it. Each element is either a ...
- 341. Flatten Nested List Iterator
List里可以有int或者List,然后里面的List里面可以再有List. 用Stack来做比较直观 Iterator无非是next()或者hasNext()这2个方程 一开始我想的是hasNext ...
- 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...
- 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...
- 【LeetCode】784. Letter Case Permutation 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 循环 日期 题目地址:https://leet ...
随机推荐
- SourceTree使用图解-转
这篇文档的目的是:让使用Git更轻松. 看完这篇文档你能做到的是: 1.简单的用Git管理项目. 2.怎样既要开发又要处理发布出去的版本bug情况. SourceTree是一个免费的Git图形化管理工 ...
- CSS3单行文本两端对齐
CSS3实现单行文本两端对齐 p { height: 24px; text-align: justify; text-last-align: justify; } p::after { display ...
- 大数据学习day17------第三阶段-----scala05------1.Akka RPC通信案例改造和部署在多台机器上 2. 柯里化方法 3. 隐式转换 4 scala的泛型
1.Akka RPC通信案例改造和部署在多台机器上 1.1 Akka RPC通信案例的改造(主要是把一些参数不写是) Master package com._51doit.akka.rpc impo ...
- 乱序拼图验证的识别并还原-puzzle-captcha
一.前言 乱序拼图验证是一种较少见的验证码防御,市面上更多的是拖动滑块,被完美攻克的有不少,都在行为轨迹上下足了功夫,本文不讨论轨迹模拟范畴,就只针对拼图还原进行研究. 找一个市面比较普及的顶像乱序拼 ...
- 【leetcode】917. Reverse Only Letters(双指针)
Given a string s, reverse the string according to the following rules: All the characters that are n ...
- android 获取uri的正确文件路径的办法
private String getRealPath( Uri fileUrl ) { String fileName = null; if( fileUrl != null ) { if( file ...
- JDBC(2):JDBC对数据库进行CRUD
一. statement对象 JDBC程序中的Connection用于代表数据库的链接:Statement对象用于向数据库发送SQL语句:ResultSet用于代表Sql语句的执行结果 JDBC中的s ...
- 【Java基础】Java 注解详解
对于Java注解,我之前的印象是很模糊的,总觉得这个东西经常听说,也经常用,但是具体是怎么回事,好像没有仔细学习过,说到注解,立马想到@Controller,仅此而已. 对于Java注解,我咨询过一些 ...
- Mysql-高性能索引策略及不走索引的例子总结
Mysql-高性能索引策略 正确的创建和使用索引是实现高性能查询的基础.我总结了以下几点索引选择的策略和索引的注意事项: 索引的使用策略: (PS:索引的选择性是指:不重复的索引值,和数据表的记录总数 ...
- linux环境centos
qhost:查看集群 投送到集群qsub -l vf=2G,p=1 work.sh -cwd -V all_section_run.sh 杀死任务 qdel id qstat -u \* |less ...