Leetcode 341. 扁平化嵌套列表迭代器(最詳細的思路解法!!!)

給定一個嵌套的整型列表。設計一個迭代器,使其能夠遍歷這個整型列表中的所有整數。

列表中的項或者爲一個整數,或者是另一個列表。

示例 1:

輸入: [[1,1],2,[1,1]]
輸出: [1,1,2,1,1]
解釋: 通過重複調用 next 直到 hasNext 返回false,next 返回的元素的順序應該是: [1,1,2,1,1]。
示例 2:

輸入: [1,[4,[6]]]
輸出: [1,4,6]
解釋: 通過重複調用 next 直到 hasNext 返回false,next 返回的元素的順序應該是: [1,4,6]。

解題思路:
首先要仔細讀懂題目及其所給的信息,當你看明白之後,其實這個題也就差不多了。大概思路是:從頭開始遍歷nestedList,若是Int直接Push進Res中,若不是,那就遞歸。

代碼如下:

/**
 * // 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(nestedList);
    }
    
    void res(vector<NestedInteger> &nestedList){
        for(auto t:nestedList){
            if(t.isInteger()){
                ans.push_back(t.getInteger());
            }
            else{
                res(t.getList());
            }
        }
    }

    int next() {
        return ans[cnt++];
    }

    bool hasNext() {
        return cnt<ans.size();
    }
private:
    vector<int> ans;
    int cnt=0;
};


/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i(nestedList);
 * while (i.hasNext()) cout << i.next();
 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章