1. 程式人生 > >Leetcode341. 扁平化巢狀列表迭代器(Flatten Nested List Iterator)

Leetcode341. 扁平化巢狀列表迭代器(Flatten Nested List Iterator)

題目描述

給定一個巢狀的整型列表。設計一個迭代器,使其能夠遍歷這個整型列表中的所有整數。
列表中的項或者為一個整數,或者是另一個列表。
示例 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]。

解題思路:

解這道題需要好好看清楚初始程式碼裡面註釋的內容,大致如下:

  1. 對於 bool isInteger() const;如果此NestedInteger包含單個整數而不是巢狀列表,則返回true。
  2. 對於 int getInteger() const;返回此NestedInteger儲存的單個整數(如果它包含單個整數),如果此NestedInteger包含巢狀列表,則結果未定義。
  3. 對於const vector < NestedInteger >&getList()const;如果它擁有巢狀列表,則返回此NestedInteger包含的巢狀列表,如果此NestedInteger包含單個整數,則結果未定義。ps:為什麼這樣用?請看超連結裡面文章關於返回值的引用章節內容。

程式碼:

/**
 * // 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: //isInteger() *類中的三個函式放在這裡時刻提醒自己* //getInteger() //getList() vector<int> ans; int cnt=0; 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(); } }; /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i(nestedList); * while (i.hasNext()) cout << i.next(); */

超連結:const引用返回值