【LeetCode】341. 扁平化嵌套列表迭代器 Flatten Nested List Iterator(C++)


题目来源:https://leetcode-cn.com/problems/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]。

题目大意

  • 每个数组中的元素类型为NestedInteger,有isInteger()、getInteger(),先判断当前元素是否时数组(有空数据),然后根据这个形式继续往下递归,遍历递归后的元素并依次push进数组

递归

/**
 * class NestedInteger {
 *   public:
 *     bool isInteger() const;
 *     int getInteger() const;
 *     const vector<NestedInteger> &getList() const;
 * };
 */
vector<int> cnt;
class NestedIterator {
    
    
public:
    int index = 0, len;
    NestedIterator(vector<NestedInteger> &nestedList) {
    
    
        for (int i = 0 ; i < nestedList.size() ; ++i){
    
    
            if (nestedList[i].getList().size() == 0){
    
    
                if (nestedList[i].isInteger())
                    cnt.push_back(nestedList[i].getInteger());
            }
            else
                NestedIterator(nestedList[i].getList());
        }
        len = cnt.size();
    }
    
    int next() {
    
    
       return cnt[index++];
    }
    
    bool hasNext() {
    
    
        if (index < len)
            return true;
        cnt.clear();
        return false;
    }
};

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i(nestedList);
 * while (i.hasNext()) cout << i.next();
 */

复杂度分析

  • 时间复杂度:O(n)。n为数组的长度,本质上遍历一遍数组中的所有元素
  • 空间复杂度:O(n)。n为数组的长度,递归栈所用空间复杂度为O(n)

猜你喜欢

转载自blog.csdn.net/lr_shadow/article/details/115118689
今日推荐