[LeetCode] 341. Flatten Nested List Iterator 压平嵌套链表迭代器
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]
.
将1个含有整数元素的嵌套链表压平,就是把所以元素按嵌套关系变成1个list。按题目要求要有next和hasNext两个函数。
Java:
public class NestedIterator implements Iterator<Integer> {
Stack<NestedInteger> stack; public NestedIterator(List<NestedInteger> nestedList) {
stack = new Stack<>();
pushData(nestedList);
} @Override
public Integer next() {
return stack.pop().getInteger();
} @Override
public boolean hasNext() {
while(!stack.isEmpty()) {
if (stack.peek().isInteger()) {
return true;
}
pushData(stack.pop().getList());
}
return false;
} private void pushData(List<NestedInteger> nestedList) {
for (int i = nestedList.size() - 1; i >= 0; i--) {
stack.push(nestedList.get(i));
}
}
} /**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/
Python: stack
# """
# 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.stack = []
self.list = nestedList def next(self):
"""
:rtype: int
"""
return self.stack.pop() def hasNext(self):
"""
:rtype: bool
"""
while self.list or self.stack:
if not self.stack:
self.stack.append(self.list.pop(0))
while self.stack and not self.stack[-1].isInteger():
top = self.stack.pop().getList()
for e in top[::-1]:
self.stack.append(e)
if self.stack and self.stack[-1].isInteger():
return True
return False # Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
Python: queue
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())
C++: stack
class NestedIterator {
public:
NestedIterator(vector<NestedInteger> &nestedList) {
for (int i = nestedList.size() - 1; i >= 0; --i) {
s.push(nestedList[i]);
}
} int next() {
NestedInteger t = s.top(); s.pop();
return t.getInteger();
} bool hasNext() {
while (!s.empty()) {
NestedInteger t = s.top();
if (t.isInteger()) return true;
s.pop();
for (int i = t.getList().size() - 1; i >= 0; --i) {
s.push(t.getList()[i]);
}
}
return false;
} private:
stack<NestedInteger> s;
};
C++:deque
class NestedIterator {
public:
NestedIterator(vector<NestedInteger> &nestedList) {
for (auto a : nestedList) {
d.push_back(a);
}
} int next() {
NestedInteger t = d.front(); d.pop_front();
return t.getInteger();
} bool hasNext() {
while (!d.empty()) {
NestedInteger t = d.front();
if (t.isInteger()) return true;
d.pop_front();
for (int i = 0; i < t.getList().size(); ++i) {
d.insert(d.begin() + i, t.getList()[i]);
}
}
return false;
} private:
deque<NestedInteger> d;
};
C++: Recursion
class NestedIterator {
public:
NestedIterator(vector<NestedInteger> &nestedList) {
make_queue(nestedList);
} int next() {
int t = q.front(); q.pop();
return t;
} bool hasNext() {
return !q.empty();
} private:
queue<int> q;
void make_queue(vector<NestedInteger> &nestedList) {
for (auto a : nestedList) {
if (a.isInteger()) q.push(a.getInteger());
else make_queue(a.getList());
}
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 341. Flatten Nested List Iterator 压平嵌套链表迭代器的更多相关文章
- [LeetCode] Flatten Nested List Iterator 压平嵌套链表迭代器
Given a nested list of integers, implement an iterator to flatten it. Each element is either an inte ...
- [LintCode] 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 解题报告(Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归+队列 栈 日期 题目地址:https://lee ...
- [Swift]LeetCode341. 压平嵌套链表迭代器 | 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 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 ...
随机推荐
- Tarjan算法分解强连通分量(附详细参考文章)
Tarjan算法分解强连通分量 算法思路: 算法通过dfs遍历整个连通分量,并在遍历过程中给每个点打上两个记号:一个是时间戳,即首次访问到节点i的时刻,另一个是节点u的某一个祖先被访问的最早时刻. 时 ...
- 使用python的jira库操作jira的版本单和问题单链接
操作JIRA的API来实现的. 但感觉比单纯操作API要简单一些. from jira import JIRA from django.conf import settings JIRA_URL = ...
- 常用conda命令【转载】
转载地址:https://haoyu.love/blog900.html 一直在用 Conda,很多东西记不住,每次都要查 Doc.那好,就写在这里做个备忘好了. 在 bash 里面自动加载 cond ...
- computed配合watch监听对象数据
- Go语言 - 函数 | 作用域 | 匿名函数 | 闭包 | 内置函数
函数是组织好的.可重复使用的.用于执行指定任务的代码块.本文介绍了Go语言中函数的相关内容. 介绍 Go语言中支持函数.匿名函数和闭包,并且函数在Go语言中属于“一等公民”. 函数可以赋值给变量 函数 ...
- KM模板 最大权匹配(广搜版) Luogu P1559 运动员最佳匹配问题
KM板题: #include <bits/stdc++.h> using namespace std; inline void read(int &num) { char ch; ...
- IDEA设置类注释和方法注释模板
背景 在日常开发中,类和方法上希望有属于自己风格的注释模板,此文将记录如何设置IDEA类和方法注释模板. 注意:如果公司有统一的规范模板,请按照公司提供的规范模板去设置,这样可以统一代码注释风格.当然 ...
- wget递归下载网站资源
wget -r -p -np -k http://archive.openwrt.org/barrier_breaker/14.07/ramips/mt7620a/packages/ 在下载https ...
- .net解决大文件断点续传
以ASP.NET Core WebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API ,包括文件的上传和下载. 准备文件上传的API #region 文件上传 ...
- 开源项目 05 Dapper
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...