微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

iOS LeetCode ☞ 扁平化嵌套列表迭代器

给你一个嵌套的整数列表 nestedList 。每个元素要么是一个整数,要么是一个列表;该列表的元素也可能是整数或者是其他列表。请你实现一个迭代器将其扁平化,使之能够遍历这个列表中的所有整数。

实现扁平迭代器类 nestedIterator

  • nestedIterator(List<nestedInteger> nestedList) 用嵌套列表 nestedList 初始化迭代器。
  • int next() 返回嵌套列表的下一个整数。
  • boolean hasNext() 如果仍然存在待迭代的整数,返回 true ;否则,返回 false

你的代码将会用下述伪代码检测:

initialize iterator with nestedList
res = []
while iterator.hasNext()
    append iterator.next() to the end of res
return res

如果 res 与预期的扁平化列表匹配,那么你的代码将会被判为正确。

示例 1:

输入:nestedList = [[1,1],2,[1,1]]
输出:[1,1,2,1,1]
解释:通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,1,2,1,1]。

示例 2:

输入:nestedList = [1,[4,[6]]]
输出:[1,4,6]
解释:通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,4,6]。

提示

  • 1 <= nestedList.length <= 500
  • 嵌套列表中的整数值在范围 [-106, 106] 内

解题思路

嵌套的整型列表是一个树形结构,树上的叶子节点对应一个整数,非叶节点对应一个列表。

在这棵树上深度优先搜索的顺序就是迭代器遍历的顺序。

我们可以先遍历整个嵌套列表,将所有整数存入一个数组,然后遍历该数组从而实现 nexthasNext 方法

代码

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class nestedInteger {
 *     // Return true if this nestedInteger holds a single integer, rather than a nested list.
 *     public func isInteger() -> Bool
 *
 *     // 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
 *     public func getInteger() -> Int
 *
 *     // Set this nestedInteger to hold a single integer.
 *     public func setInteger(value: Int)
 *
 *     // Set this nestedInteger to hold a nested list and adds a nested integer to it.
 *     public func add(elem: nestedInteger)
 *
 *     // 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
 *     public func getList() -> [nestedInteger]
 * }
 */

// 341. 扁平化嵌套列表迭代器
class nestedIterator {

    var list: [Int] = [Int]()
    
    init(_ nestedList: [nestedInteger]) {
        dfs(nestedList)
    }
    
    private func dfs(_ nestedList: [nestedInteger]) {
        for val in nestedList {
            if val.isInteger() {
                list.append(val.getInteger())
            } else {
                dfs(val.getList())
            }
        }
    }
    
    func next() -> Int {
        
        return list.removeFirst()
    }
    
    func hasNext() -> Bool {
        
        return list.count > 0
    }
}

/**
 * Your nestedIterator object will be instantiated and called as such:
 * let obj = nestedIterator(nestedList)
 * let ret_1: Int = obj.next()
 * let ret_2: Bool = obj.hasNext()
 */

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐