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].
Explain
這道題最核心的意思就是把一個可能會嵌套很多層的數(shù)組扁平化习瑰。那無疑是得使用遞歸的猾编。我們從頭到尾遍歷一次,如果是數(shù)字就push進vector虱疏,如果是一個數(shù)組就調(diào)用遞歸函數(shù),等待這個數(shù)組扁平化后钾菊,再將數(shù)組內(nèi)的每一項push進vector里面慢哈。除此之外呢, 這道題會有幾個極端的例子绊汹,就是數(shù)組為空磺箕,數(shù)組嵌套的數(shù)組為空的情況奖慌,注意判斷就好。那么下面就是實現(xiàn):
Code
/**
* // 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) {
res = helper(nestedList);
}
int next() {
pos++;
return res[pos - 1];
}
bool hasNext() {
return !res.empty() && res.size() - 1 >= pos;
}
private:
vector<int> res;
int pos = 0;
vector<int> helper(vector<NestedInteger> &nestedList) {
vector<int> res;
if (nestedList.empty()) return res;
for (int i = 0; i < nestedList.size(); i++) {
if (nestedList[i].isInteger()) {
res.push_back(nestedList[i].getInteger());
} else {
vector<int> cur = helper(nestedList[i].getList());
for (auto c : cur) {
res.push_back(c);
}
}
}
return res;
}
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/