力扣labuladong一刷day38天扁平化嵌套列表迭代器

力扣labuladong一刷day38天扁平化嵌套列表迭代器

一、341. 扁平化嵌套列表迭代器

题目链接:https://leetcode.cn/problems/flatten-nested-list-iterator/description/

思路:本题是一个嵌套列表,如果一次性全部给拉平迭代到一维占用的内存可能过大。我们采用惰性加载,因为使用的时候是先判断hasNext()然后才调用next,每次当判断hasNext()的时候,如果list中第一个元素是list那么就惰性加载给展开,展开的时候就把当前局部的list倒序添加都原list索引为0的位置。

java 复制代码
 public class NestedIterator implements Iterator<Integer> {

        private LinkedList<NestedInteger> list;
        public NestedIterator(List<NestedInteger> nestedList) {
            list = new LinkedList<>(nestedList);
        }

        @Override
        public Integer next() {
            return list.remove(0).getInteger();
        }

        @Override
        public boolean hasNext() {
            while (!list.isEmpty() && !list.get(0).isInteger()) {
                List<NestedInteger> nList = list.remove(0).getList();
                for (int i = nList.size()-1; i >= 0; i--) {
                    list.addFirst(nList.get(i));
                }
            }
            return !list.isEmpty();
        }
    }

附题目数据类型:

java 复制代码
public class NestedInteger {
    // 如果其中存的是一个整数,则返回 true,否则返回 false
    public boolean isInteger();

    // 如果其中存的是一个整数,则返回这个整数,否则返回 null
    public Integer getInteger();

    // 如果其中存的是一个列表,则返回这个列表,否则返回 null
    public List<NestedInteger> getList();
}
相关推荐
倔强的小石头_8 分钟前
【C语言指南】函数指针深度解析
java·c语言·算法
Yasin Chen13 分钟前
C# Dictionary源码分析
算法·unity·哈希算法
_Coin_-1 小时前
算法训练营DAY27 第八章 贪心算法 part01
算法·贪心算法
董董灿是个攻城狮6 小时前
5分钟搞懂什么是窗口注意力?
算法
Dann Hiroaki6 小时前
笔记分享: 哈尔滨工业大学CS31002编译原理——02. 语法分析
笔记·算法
qqxhb7 小时前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
FirstFrost --sy9 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
森焱森9 小时前
垂起固定翼无人机介绍
c语言·单片机·算法·架构·无人机
搂鱼11451410 小时前
(倍增)洛谷 P1613 跑路/P4155 国旗计划
算法
Yingye Zhu(HPXXZYY)10 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法