LeetCode 341 Flatten Nested List Iterator
概述
https://leetcode.com/problems/flatten-nested-list-iterator/
递归法
class NestedIterator {
public:
vector<int> list;
int idx = 0;
NestedIterator(vector<NestedInteger> &nestedList) {
helper(nestedList);
}
void helper(vector<NestedInteger> &nestedList) {
for (auto e : nestedList) {
if (e.isInteger()) {
list.push_back(e.getInteger());
} else {
helper(e.getList());
}
}
}
int next() {
return list[idx++];
}
bool hasNext() {
return idx < list.size();
}
};
迭代法
https://mp.weixin.qq.com/s/uEmD5YVGG5LHQEmJQ2GSfw
大致思想是调用 hasNext 时保证第一个元素为 int,而非列表,如果是列表,就将其拆开放到前面,知道第一个不是列表位置。