341 扁平化嵌套列表迭代器

本文最后更新于:2021年1月23日 晚上

给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。

列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。

示例 1:

1
2
3
输入: [[1,1],2,[1,1]]
输出: [1,1,2,1,1]
解释: 通过重复调用 next 直到 hasNext 返回 falsenext 返回的元素的顺序应该是: [1,1,2,1,1]。

示例 2:

1
2
3
输入: [1,[4,[6]]]
输出: [1,4,6]
解释: 通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,4,6]

Solution

yexiso 从题目给出的输入和输出可以看出,官方的测试会将扁平化嵌套列表中的所有元素全部输出。
所有可有有两种思路:
①在遍历的同时,输出元素;

参考:《算法小抄》4.10 、**@hsyv5897**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# @lc code=start
# """
# 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]):
# 对于nestedList中的内容,我们需要从左往右遍历,
# 但堆栈pop是从右端开始,所以我们压栈的时候需要将nestedList反转再压栈
self.stack = nestedList[::-1]

def next(self) -> int:
# hasNext 函数中已经保证栈顶是integer,所以直接返回pop结果
return self.stack.pop(-1).getInteger()

def hasNext(self) -> bool:
# 对栈顶进行‘剥皮’,如果栈顶是List,把List反转再依次压栈,
# 然后再看栈顶,依次循环直到栈顶为Integer。
# 同时可以处理空的List,类似[[[]],[]]这种test case
while len(self.stack) > 0 and self.stack[-1].isInteger() is False:
self.stack += self.stack.pop().getList()[::-1]
return len(self.stack) > 0

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
# @lc code=end

②在构造函数中直接解析所有元素(用数组保存),然后在遍历时依次输出即可。

参考 liuyuboboboyexiso

DFS

其实要解析一个扁平化嵌套列表,思路与dfs非常类似,将vector当作一个非连通图,每个NestedInteger是一个连通图,里面存了各个节点及其所有的邻接点。

然后在遍历每个图时,只要遇到整型Integer,直接输出,如果是列表vector,递归访问该列表中的所有节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// @lc code=start
/**
* // 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 {
private:
vector<int> data;
int i;
public:
NestedIterator(vector<NestedInteger> &nestedList) {
dfs(nestedList);
i = 0;
}

int next() {
return data[i++];
}

bool hasNext() {
return i<data.size();
}

private:
void dfs(const vector<NestedInteger>& nestedList){
for(const NestedInteger& e: nestedList){
if(e.isInteger())
data.push_back(e.getInteger());
else
dfs(e.getList());
}
}
};

/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/
// @lc code=end

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!