LeetCode——341. 扁平化嵌套列表迭代器(Flatten Nested List Iterator)[中等]——分析及代码(Java)

LeetCode——341. 扁平化嵌套列表迭代器[Flatten Nested List Iterator][中等]——分析及代码[Java]

一、题目

给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。
列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。

示例 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]。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-nested-list-iterator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、分析及代码

1. 深度优先搜索

(1)思路

嵌套的整型列表实际结构类似于树,可从根节点出发进行深度优先搜索,遇到整数节点直接存储其数值,遇到子列表则先深入子列表进行搜索,直至完成遍历。

(2)代码

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
public class NestedIterator implements Iterator<Integer> {
    
    
    private List<Integer> nums;//整理后的整数列表
    private Iterator<Integer> its;//指向当前整数的指针

    public NestedIterator(List<NestedInteger> nestedList) {
    
    
        nums = new ArrayList<>();
        dfs(nestedList);//深度优先搜索
        its = nums.iterator();//初始化指针
    }

    @Override
    public Integer next() {
    
    
        return its.next();
    }

    @Override
    public boolean hasNext() {
    
    
        return its.hasNext();
    }

    public void dfs(List<NestedInteger> nestedList) {
    
    
        for (NestedInteger nest : nestedList) {
    
    
            if (nest.isInteger())//当前位置为整数,直接加入列表
                nums.add(nest.getInteger());
            else//当前位置为列表,遍历该列表
                dfs(nest.getList());
        }
    }
}

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i = new NestedIterator(nestedList);
 * while (i.hasNext()) v[f()] = i.next();
 */

(3)结果

执行用时 :3 ms,在所有 Java 提交中击败了 91.05% 的用户;
内存消耗 :41.2 MB,在所有 Java 提交中击败了 5.15% 的用户。

三、其他

还可进一步结合栈,用迭代代替递归。

猜你喜欢

转载自blog.csdn.net/zml66666/article/details/115149668
今日推荐