每日一题 341. 扁平化嵌套列表迭代器
341. 扁平化嵌套列表迭代器
展开成数组来解题
class NestedIterator {
vector<int> nums;
int idx;
void flattened(vector<NestedInteger> &nestedList)
{
for(int i=0;i<nestedList.size();++i)
{
if(nestedList[i].isInteger())
{
nums.push_back(nestedList[i].getInteger());
}else{
flattened(nestedList[i].getList());
}
}
}
public:
NestedIterator(vector<NestedInteger> &nestedList) {
idx = 0;
flattened(nestedList);
}
int next() {
return nums[idx++];
}
bool hasNext() {
return idx < nums.size();
}
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/