数据结构与算法之栈: LeetCode 341. 扁平化嵌套列表迭代器 (Ts版)

Java实现 LeetCode 341 扁平化嵌套列表迭代器 341. 扁平化嵌套列表迭代器 给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。 示例 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 返回的元素的顺序应该是: 立即下载

扁平化嵌套列表迭代器

描述

  • 给你一个嵌套的整数列表 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
  • 嵌套列表中的整数值在范围 [- 1 0 6 10^6 106, 1 0 6 10^6 106] 内

Typescript 版算法实现


1 ) 方案1:深度优先搜索

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *     If value is provided, then it holds a single integer
 *     Otherwise it holds an empty nested list
 *     constructor(value?: number) {
 *         ...
 *     };
 *
 *     Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     isInteger(): boolean {
 *         ...
 *     };
 *
 *     Return the single integer that this NestedInteger holds, if it holds a single integer
 *     Return null if this NestedInteger holds a nested list
 *     getInteger(): number | null {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a single integer equal to value.
 *     setInteger(value: number) {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
 *     add(elem: NestedInteger) {
 *         ...
 *     };
 *
 *     Return the nested list that this NestedInteger holds,
 *     or an empty list if this NestedInteger holds a single integer
 *     getList(): NestedInteger[] {
 *         ...
 *     };
 * };
 */

class NestedIterator {
    vals = []
    constructor(nestedList: NestedInteger[]) {
		this.vals = [];
        const dfs = (nestedList) => {
            for (const nest of nestedList) {
                if (nest.isInteger()) {
                    this.vals.push(nest.getInteger());
                } else {
                    dfs(nest.getList());
                }
            }
        }
        dfs(nestedList);
    }

    hasNext(): boolean {
		return this.vals.length > 0;
    }

	next(): number {
		const val = this.vals[0];
        this.vals = this.vals.slice(1);
        return val;
    }
}

/**
 * Your ParkingSystem object will be instantiated and called as such:
 * var obj = new NestedIterator(nestedList)
 * var a: number[] = []
 * while (obj.hasNext()) a.push(obj.next());
 */

2 ) 方案2:栈

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *     If value is provided, then it holds a single integer
 *     Otherwise it holds an empty nested list
 *     constructor(value?: number) {
 *         ...
 *     };
 *
 *     Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     isInteger(): boolean {
 *         ...
 *     };
 *
 *     Return the single integer that this NestedInteger holds, if it holds a single integer
 *     Return null if this NestedInteger holds a nested list
 *     getInteger(): number | null {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a single integer equal to value.
 *     setInteger(value: number) {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
 *     add(elem: NestedInteger) {
 *         ...
 *     };
 *
 *     Return the nested list that this NestedInteger holds,
 *     or an empty list if this NestedInteger holds a single integer
 *     getList(): NestedInteger[] {
 *         ...
 *     };
 * };
 */

class NestedIterator {
    stack = []
    constructor(nestedList: NestedInteger[]) {
		this.stack = nestedList;
    }

    hasNext(): boolean {
		while (this.stack.length !== 0) {
            if (this.stack[0].isInteger()) {
                return true;
            } else {
                let cur = this.stack[0].getList();
                this.stack.shift();
                this.stack.unshift(...cur);
            }
        }
    }

	next(): number {
		return this.stack.shift().getInteger();
    }
}

/**
 * Your ParkingSystem object will be instantiated and called as such:
 * var obj = new NestedIterator(nestedList)
 * var a: number[] = []
 * while (obj.hasNext()) a.push(obj.next());
 */

3 ) 方案3:另一种栈

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *     If value is provided, then it holds a single integer
 *     Otherwise it holds an empty nested list
 *     constructor(value?: number) {
 *         ...
 *     };
 *
 *     Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     isInteger(): boolean {
 *         ...
 *     };
 *
 *     Return the single integer that this NestedInteger holds, if it holds a single integer
 *     Return null if this NestedInteger holds a nested list
 *     getInteger(): number | null {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a single integer equal to value.
 *     setInteger(value: number) {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
 *     add(elem: NestedInteger) {
 *         ...
 *     };
 *
 *     Return the nested list that this NestedInteger holds,
 *     or an empty list if this NestedInteger holds a single integer
 *     getList(): NestedInteger[] {
 *         ...
 *     };
 * };
 */

// 假设 NestedInteger 接口已经定义好,这里提供一个简化版本
interface NestedInteger {
    isInteger(): boolean;
    getInteger(): number;
    getList(): NestedInteger[];
}

class NestedIterator {
    private list: number[] = [];
    private index: number = 0;

    constructor(nestedList: NestedInteger[]) {
        this.flatArray(nestedList);
    }

    private flatArray(arr: NestedInteger[]): void {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].isInteger()) {
                this.list.push(arr[i].getInteger());
            } else {
                this.flatArray(arr[i].getList());
            }
        }
    }

    hasNext(): boolean {
        return this.index < this.list.length;
    }

    next(): number {
        if (this.hasNext()) {
            return this.list[this.index++];
        }
        throw new Error('No more elements');
    }
}

// 辅助函数 flatArray 的 TypeScript 版本
function flatArray(arr: any[]): any[] {
    const stack = [...arr];
    const ret: any[] = [];
    while (stack.length) {
        let next = stack.pop();
        if (Array.isArray(next)) {
            stack.push(...next);
        } else {
            ret.unshift(next); // 使用 unshift 来保持原始顺序
        }
    }
    return ret;
}

/**
 * Your ParkingSystem object will be instantiated and called as such:
 * var obj = new NestedIterator(nestedList)
 * var a: number[] = []
 * while (obj.hasNext()) a.push(obj.next());
 */
LPDDR5电路设计的新功能 本文从硬件电路设计的角度,简述了LPDDR5 JEDEC标准中新增的功能。 阅读详情

相关推荐

HDR标准核心参数全解析:从PQ/HLG到元数据,一篇搞懂技术选型

本文全面解析HDR标准的核心参数,包括PQ/HLG传输函数和元数据机制,帮助读者理解技术选型的关键因素。通过对比主流HDR标准的技术细节,提供从内容创作到硬件适配的实用指南,助力实现更真实的视觉体验。

weixin_31766003的博客 302

LeetCode-341-扁平化嵌套列表迭代器

本题实际上是在遍历一棵树,将每个节点上的值加入最后的数组中,并返回数组的指针。我们可以使用深度优先遍历通过递归来遍历整个嵌套数组。我们首先定义dfs函数,对于nestedList中的每一个元素,若为整数则直接加入最终的数组,否则直接递归调用构造函数新建指针进行扁平化处理。在构造函数中,我们只需要深度遍历整棵树,并将指针指向开头即可。对于next,我们只需要返回当前指针的下一个值即可。对于hasNext,我们只需要判断当前指针是否指向末尾即可。

L.Wzz的博客 238

基于carsim与Simulink联合仿真的车辆换道轨迹规划与轨迹跟踪模型

PID_反步控制_滑膜控制三种四旋翼无人机轨迹跟踪控制算法仿真 附带对应的说明文档,提供建模过程与仿真结果文献(英文)➕PPT 描述:采用的同一种参考轨迹,都是三维仿真 三种控制方法: [1]PID控制、[2]反步控制、[3]滑膜控制(三个仿真模型) 每个仿真均应用了同一种轨迹路径,直接运行即可出三维图,可以实现四旋翼无人机轨迹的跟踪

2501_90804007的博客 1087

扁平化嵌套列表迭代器

扁平化嵌套列表迭代器

青釉Oo的博客 554

最终篇——SWAT模型的建立

同理,Soil Data也是同样的方法导入,在Soil Database Options的选项中,选择UserSiol,用同样的方法导入土壤类型,进行重分类。打开窗口后,只定义HRU Thresholdes,其余两个不用设置,设定各数据单元的计算率,这里的10%的意思是计算精度,即分成级HRU计算单元太小,小于平均计算单元的10%,我们就不对这HRU单元进行计算(也就是说太破碎的计算单元不进行计算),若选择0%意味着全部进行计算,需要耗费大量的内存和时间,对计算机要求较高,不建议。

m0_72556434的博客 5623

微生物16S数据上传NCBI的SRA库

本篇内容仅包括:俺自己的实验收集了淡水、淡水沉积物、海水、海草附着微生物样品,测序所得的Fastq格式数据,在文章投稿发表时被要求数据需上传NCBI的SRA库,得到一个PRJNA2347899这样子的IDs。仅解决了这个上传过程!

Xf_Niu的博客 7437

341.扁平化嵌套列表迭代器 | N叉树的最大深度

该列表的元素也可能是整数或者是其他列表。请你实现一个迭代器将其扁平化,使之能够遍历这个列表中的所有整数。解释:通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,1,2,1,1]。如果 res 与预期的扁平化列表匹配,那么你的代码将会被判为正确。输入:root = [1,null,3,2,4,null,5,6]输入:nestedList = [[1,1],2,[1,1]]int next() 返回嵌套列表的下一个整数。输出:[1,1,2,1,1]...

weixin_50437588的博客 208

生信物种注释软件Kraken2+Bracken的安装与使用

一、软件安装与数据库下载 1.Kraken2安装 Kraken2是一个基于k-mer算法的高精度宏基因组序列分类软件,能够快速的将测序reads进行物种分类。 使用conda一键安装,要先安装好anaconda或者miniconda conda install -y kraken2 输入krakek2 --help 出现如下所示帮助文档,则表示安装成功。 2.Bracken安装 bracken是一种从宏基因组数据中高度准确的计算物种丰度的统计方法。 同样使用conda一键安装 conda install -

jileiqwd的博客 1万+

LeetCode题练习与总结:扁平化嵌套列表迭代器--341

本文详细介绍了如何实现一个扁平化嵌套整数列表的迭代器,包括解题思路、具体代码实现、时间复杂度和空间复杂度分析,以及涉及的知识点总结,为解决此类问题提供了清晰的指导。

一直学习永不止步 1221

【Docker】掌握 Docker魔法:Windows 11 平台上的完美容器部署终极指南

【Docker】掌握 Docker魔法:Windows 11 平台上的完美容器部署终极指南 一文搞懂什么是 Docker?分析容器的工作原理、容器的架构、Docker的优势、使用 Docker的原因。 全程手把手教你Docker的安装与使用,配置阿里云镜像加速、容器常用命令!

寸铁的博客 10万+

YOLOv11改进策略【Neck】| SEAM:分离和增强注意模块,解决复杂场景下的小目标遮挡问题

本文记录的是利用 SEAM 模块优化 YOLOv11 的目标检测网络模型。的设计出发点在于解决复杂场景下的人脸遮挡问题,相当于是小目标被其他物体部分遮挡时,传统方法因特征缺失导致检测精度下降的问题。该模块通过增强未遮挡区域的特征响应并补偿被遮挡区域的信息损失,提升模型对遮挡小目标的检测能力。YOLO-FaceV2: A Scale and Occlusion Aware Face DetectorSEAM模块(Separated and Enhancement Attention Module)的设计出发点

Limiiiing的博客 2281

(Leetcode) 扁平化嵌套列表迭代器 - Python实现

题目:扁平化嵌套列表迭代器 给定一个嵌套的整型列表。设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的项或者为一个整数,或者是另一个列表。示例: 输入: [[1,1],2,[1,1]],输出: [1,1,2,1,1] 解释: 通过重复调用 next 直到 hasNext 返回false,next 返回的元素的顺序应该是: [1,1,2,1,1]。 输入: [1,[4,[6]]],输出...

weixin_42077402的博客 549

osg中显示3dtiles和cesiumIon

如下图为CesiumTilesetNode数据更新相关代码,将OSG对应的ViewMatrix、ProjectionMatrix和窗口信息传递给tileset->updateView()实现Cesium-native的场景更新。整体结构,其中 CesiumTilesetNode依赖Cesium3DTilesSelection::Tileset,实现数据的更新以及确定需要绘制的节点。1.1 CesiumNative3DTileslayer图层。

CPWWHSU的博客 890

LeetCode 341. 扁平化嵌套列表迭代器(C++)

给你一个嵌套的整数列表 nestedList 。每个元素要么是一个整数,要么是一个列表;该列表的元素也可能是整数或者是其他列表。请你实现一个迭代器将其扁平化,使之能够遍历这个列表中的所有整数。 NestedIterator(List nestedList) 用嵌套列表 nestedList 初始化迭代器。int next() 返回嵌套列表的下一个整数。boolean hasNext() 如果仍然存在待迭代的整数,返回 true ;否则,返回 false 。

Panbk的博客 404

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

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

题目描述 341. 扁平化嵌套列表迭代器 解法:递归 这道题最重要的是先理解题意,在理解的情况下,其实我们要做的就是一棵 N 叉树的遍历,为什么这样说呢? 比如说输入是 [[1,1],2,[1,1]][[1,1],2,[1,1]][[1,1],2,[1,1]],其实就是如下树状结构: 把一个 NestedInteger 扁平化就等价于遍历一棵 N 叉树的所有「叶子节点」,我把所有叶子节点都拿出来,不就可以作为迭代器进行遍历了吗? 有了如此思路,下面的代码就容易解决了 /** * // This is t

Aries_young的博客 367

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

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

难度:中等 题目描述: 思路总结: 方法一:用递归扁平化整个list 方法二:用栈在调用hasNext()的时候找到下一个元素 题解一: # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its impleme...

个人记录使用 248

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

栈---扁平化嵌套列表迭代器

题目 给定一个嵌套的整型列表。设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的项或者为一个整数,或者是另一个列表。 示例 输入: [[1,1],2,[1,1]] 输出: [1,1,2,1,1] 解释: 通过重复调用 next 直到 hasNext 返回false,next 返回的元素的顺序应该是: [1,1,2,1,1]。 输入: [1,[4,[6]]] 输出: [1,4,6...

AndyJson的博客 520

Leetcode【高级】 扁平化嵌套列表迭代器 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]]] 输出:...

qq_43491066的博客 356

LeetCode 扁平化嵌套列表迭代器

给定一个嵌套的整型列表。设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的项或者为一个整数,或者是另一个列表。 示例 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...

hestyle的博客 774

341. Flatten Nested List Iterator

/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Return t

jingmiaa的博客 724

LeetCode-Python-341. 扁平化嵌套列表迭代器

给定一个嵌套的整型列表。设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的项或者为一个整数,或者是另一个列表。 示例 1: 输入: [[1,1],2,[1,1]] 输出: [1,1,2,1,1] 解释: 通过重复调用next 直到hasNext 返回false,next返回的元素的顺序应该是: [1,1,2,1,1]。 示例 2: 输入: [1,[4,[6]]] 输出:...

Keep Coding 936

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

基本思路:题目看着很吓人,仔细理解之后就很简单了,NestedInteger类其实就是一个数据结构,他里面只有两种东西,一个是vector&lt;NestedInteger&gt;,和Int。这就很简单了,从头开始遍历nestedList,若是Int直接Push进Res中,若不是,那就递归。函数next和函数hasNext都是基本的东西,就不细说了。下面AC解: AC解: class Nes...

liaoxuda_edu的博客 850

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

给定一个嵌套的整型列表。设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的项或者为一个整数,或者是另一个列表。 示例 1: 输入: [[1,1],2,[1,1]] 输出: [1,1,2,1,1] 解释: 通过重复调用next 直到hasNext 返回false,next返回的元素的顺序应该是: [1,1,2,1,1]。 示例 2: 输入: [1,[4,[6]]] ...

Umbrella Corporation 8664

LintCode: 摊平嵌套的列表

给你一个嵌套的列表,实现一个迭代器将其摊平。 一个列表的每个元素可能是整数或者一个列表。 您在真实的面试中是否遇到过这个题?  Yes 样例 给出列表 [[1,1],2,[1,1]],经过迭代器之后返回 [1,1,2,1,1]。 给出列表 [1,[4,[6]]],经过迭代器之后返回 [1,4,6]。 标签  递归 栈 数据结构设计

zyf19930610的专栏 767

LeetCode - 341 扁平化嵌套列表迭代器

public class NestedIterator implements Iterator<Integer> { private List<Integer> vals; //Java Iterator(迭代器)不是一个集合,它是一种用于访问集合的方法,可用于迭代 ArrayList 和 HashSet 等集合。 private Iterator<Integer> cur; public NestedIterator(List&lt..

qq_44822951的博客 318

数据结构与算法笔记:字典序最大问题分析

字典序最大问题 问题描述 给定一个1到n的排列(无序状态的),依次插入到栈中,在每时每刻都可以多次从栈中弹出栈顶 问:应如何使得弹出栈顶的序列的字典序最大,并输出这个序列 问题分析 什么是字典序 比如两个序列:5,4,3,2,1和1,2,3,4,5 这两个中第一个的字典序最大 每个位置上的数字比其他序列上同一位置的数字要大 比如:第一位置中5比1大,第二位置中4比2大这样 即:字典序最大 = 从左向右看这个序列,每个数字都尽量大 题目给定一个1到n的排列,每个数字只出现一次 要使出栈的字典序最大

Wang的专栏 4396
上一篇: 数据结构与算法之推理: LeetCode 292. Nim 游戏 (Ts版)
下一篇: 数据结构与算法之数组: LeetCode 380. O(1) 时间插入、删除和获取随机元素 (Ts版)
Wang's Blog
博客等级 码龄12年 7440粉丝 2427原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值