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

這道題最核心的意思就是把一個(gè)可能會(huì)嵌套很多層的數(shù)組扁平化。那無疑是得使用遞歸的。我們從頭到尾遍歷一次,如果是數(shù)字就push進(jìn)vector,如果是一個(gè)數(shù)組就調(diào)用遞歸函數(shù),等待這個(gè)數(shù)組扁平化后,再將數(shù)組內(nèi)的每一項(xiàng)push進(jìn)vector里面。除此之外呢, 這道題會(huì)有幾個(gè)極端的例子,就是數(shù)組為空,數(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();
 */

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容