Leetcode-Flatten Nested List Iterator

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

这道题最核心的意思就是把一个可能会嵌套很多层的数组扁平化。那无疑是得使用递归的。我们从头到尾遍历一次,如果是数字就push进vector,如果是一个数组就调用递归函数,等待这个数组扁平化后,再将数组内的每一项push进vector里面。除此之外呢, 这道题会有几个极端的例子,就是数组为空,数组嵌套的数组为空的情况,注意判断就好。那么下面就是实现:

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();
 */

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容