LeetCode 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 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].


本题自定义了一个【嵌套的整数】,【嵌套的整数】可以是一个真正的整数,也可以是一个包含整数的数组。现在要实现针对【嵌套的整数】的一个迭代器,迭代器包含next()和hasNext()函数。 解题思路是先解析这个【嵌套的整数】数组,解析的方法就是递归的解析,把解析出来的真正的整数存到一个vector数组中。接下来的迭代器就好实现了,用pos表示当前访问的数组下标,next()函数先访问pos指向元素,然后++pos;hasNext()就判断一下pos是否走到末尾了。 完整代码如下: [cpp] class NestedIterator { private: vector<int> vi; int pos; public: void parseNestedInteger(NestedInteger& ni) { if (ni.isInteger())vi.push_back(ni.getInteger()); else { vector<NestedInteger> vni = ni.getList(); for (int i = 0; i < vni.size(); ++i) { parseNestedInteger(vni[i]); } } } NestedIterator(vector<NestedInteger> &nestedList) { for (int i = 0; i < nestedList.size(); ++i) { parseNestedInteger(nestedList[i]); } pos = 0; } int next() { return vi[pos++]; } bool hasNext() { return pos < vi.size(); } }; [/cpp] 本代码提交AC,用时29MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *