2021-8-16 341. 扁平化嵌套列表迭代器(dfs,栈)

2024-03-10 21:18

本文主要是介绍2021-8-16 341. 扁平化嵌套列表迭代器(dfs,栈),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

注:

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

实现扁平迭代器类 NestedIterator :

NestedIterator(List 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] 内

题解:
方法一 dfs
思路
嵌套的整型列表是一个树形结构,树上的叶子节点对应一个整数,非叶节点对应一个列表。

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

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

复杂度分析
时间复杂度:初始化为 O(n),next 和 hasNext 为 O(1)。其中 nn 是嵌套的整型列表中的元素个数。

空间复杂度:O(n)。需要一个数组存储嵌套的整型列表中的所有元素。

/*** // This is the interface that allows for creating nested lists.* // You should not implement it, or speculate about its implementation* class NestedInteger {*   public:*     // Return true if this NestedInteger holds a single integer, rather than a nested list.*     bool isInteger() const;**     // 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*     int getInteger() const;**     // 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*     const vector<NestedInteger> &getList() const;* };*/class NestedIterator {
public:vector<int> result;vector<int>::iterator cur;void dfs(vector<NestedInteger> lists){for(auto list:lists){if(list.isInteger()){result.push_back(list.getInteger());}else{dfs(list.getList());}}} NestedIterator(vector<NestedInteger> &nestedList) {dfs(nestedList);cur=result.begin();}int next() {return *(cur++);}bool hasNext() {return cur!=result.end();}
};/*** Your NestedIterator object will be instantiated and called as such:* NestedIterator i(nestedList);* while (i.hasNext()) cout << i.next();*/

方法二 栈
思路
我们可以用一个栈来代替方法一中的递归过程。

具体来说,用一个栈来维护深度优先搜索时,从根节点到当前节点路径上的所有节点。由于非叶节点对应的是一个列表,我们在栈中存储的是指向列表当前遍历的元素的指针(下标)。每次向下搜索时,取出列表的当前指针指向的元素并将其入栈,同时将该指针向后移动一位。如此反复直到找到一个整数。循环时若栈顶指针指向了列表末尾,则将其从栈顶弹出。

复杂度分析
时间复杂度:初始化和next 为 O(1),hasNext 为均摊 O(1)。

空间复杂度:O(n)。最坏情况下嵌套的整型列表是一条链,我们需要一个 O(n) 大小的栈来存储链上的所有元素。

/*** // This is the interface that allows for creating nested lists.* // You should not implement it, or speculate about its implementation* class NestedInteger {*   public:*     // Return true if this NestedInteger holds a single integer, rather than a nested list.*     bool isInteger() const;**     // 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*     int getInteger() const;**     // 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*     const vector<NestedInteger> &getList() const;* };*/class NestedIterator {
public:stack<pair<vector<NestedInteger>::iterator,vector<NestedInteger>::iterator>> stk;NestedIterator(vector<NestedInteger> &nestedList) {stk.emplace(nestedList.begin(),nestedList.end());}int next() {return stk.top().first++->getInteger();}bool hasNext() {while(!stk.empty()){pair<vector<NestedInteger>::iterator,vector<NestedInteger>::iterator> &p=stk.top();if(p.first==p.second){stk.pop();continue;}// 若当前元素为整数,则返回trueif(p.first->isInteger()==true){return true;}// 若当前元素为列表,则将其入栈,且迭代器p指向下一个元素vector<NestedInteger> &t=p.first++->getList();stk.emplace(t.begin(),t.end());}return false;}
};/*** Your NestedIterator object will be instantiated and called as such:* NestedIterator i(nestedList);* while (i.hasNext()) cout << i.next();*/

这篇关于2021-8-16 341. 扁平化嵌套列表迭代器(dfs,栈)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/795526

相关文章

16.Spring前世今生与Spring编程思想

1.1.课程目标 1、通过对本章内容的学习,可以掌握Spring的基本架构及各子模块之间的依赖关系。 2、 了解Spring的发展历史,启发思维。 3、 对 Spring形成一个整体的认识,为之后的深入学习做铺垫。 4、 通过对本章内容的学习,可以了解Spring版本升级的规律,从而应用到自己的系统升级版本命名。 5、Spring编程思想总结。 1.2.内容定位 Spring使用经验

一道经典Python程序样例带你飞速掌握Python的字典和列表

Python中的列表(list)和字典(dict)是两种常用的数据结构,它们在数据组织和存储方面有很大的不同。 列表(List) 列表是Python中的一种有序集合,可以随时添加和删除其中的元素。列表中的元素可以是任何数据类型,包括数字、字符串、其他列表等。列表使用方括号[]表示,元素之间用逗号,分隔。 定义和使用 # 定义一个列表 fruits = ['apple', 'banana

Python分解多重列表对象,isinstance实现

“”“待打印的字符串列表:['ft','bt',['ad',['bm','dz','rc'],'mzd']]分析可知,该列表内既有字符对象,又有列表对象(Python允许列表对象不一致)现将所有字符依次打印并组成新的列表”“”a=['ft','bt',['ad',['bm','dz','rc'],'mzd']]x=[]def func(y):for i in y:if isinst

中国341城市生态系统服务价值数据集(2000-2020年)

生态系统服务反映了人类直接或者间接从自然生态系统中获得的各种惠益,对支撑和维持人类生存和福祉起着重要基础作用。目前针对全国城市尺度的生态系统服务价值的长期评估还相对较少。我们在Xie等(2017)的静态生态系统服务当量因子表基础上,选取净初级生产力,降水量,生物迁移阻力,土壤侵蚀度和道路密度五个变量,对生态系统供给服务、调节服务、支持服务和文化服务共4大类和11小类的当量因子进行了时空调整,计算了

【Qt6.3 基础教程 16】 掌握Qt中的时间和日期:QTimer和QDateTime的高效应用

文章目录 前言QTimer:定时任务的强大工具QTimer的基本用法高级特性:单次定时器 QDateTime:处理日期和时间获取当前日期和时间日期和时间的格式化输出日期和时间计算 用例:创建一个倒计时应用结论 前言 在开发桌面应用程序时,处理时间和日期是一个常见且重要的任务。Qt框架提供了强大的工具来处理与时间相关的功能,其中QTimer和QDateTime是最核心的类。本

CSS列表属性:list-style系列属性详解

CSS(层叠样式表)是用于控制网页样式的一种语言,它允许开发者以一种非常灵活的方式来设置网页元素的外观。在CSS中,list-style属性族是专门用来设置列表样式的。列表是网页设计中常见的元素,它们可以是有序列表(<ol>)或无序列表(<ul>)。list-style系列属性允许你自定义列表项前的标记,包括类型、位置和图像。 1. list-style-type list-style-typ

STL迭代器的基础应用

STL迭代器的应用 迭代器的定义方法: 类型作用定义方式正向迭代器正序遍历STL容器容器类名::iterator 迭代器名常量正向迭代器以只读方式正序遍历STL容器容器类名::const_iterator 迭代器名反向迭代器逆序遍历STL容器容器类名::reverse_iterator 迭代器名常量反向迭代器以只读方式逆序遍历STL容器容器类名::const_reverse_iterato

Linux float int和16进制互相转换

Linux 上float int和16进制互换操作。之前把float转16进制,也就是转成4个字节,方便使用串口传输嘛。使用的方法是: //float 转 16进制float x_pid_p = 15.0;unsigned char * bValue = (unsigned char *)& x_pid_p;printf("%x\t%x\t%x\t%x\n", bValue[0], bVa

nodejs基础教程-简单blog(8)--展示用户注册信息列表

本节课展示用户注册信息列表;当点击导航栏的“用户管理”浏览器跳转路由/admin/user 显示用户列表。 先上效果图; 开始 1,在layout.html模板中导航标签中设置路径; 2,新建文件 views/admin/user_index.html,在admin.js中设置user_index的路由为/admin/user;并查询数据库所有用户的信息 返回给前台users;

2021-02-16物料档案条码添加和蓝牙条码标签打印,金蝶安卓盘点机PDA,金蝶仓库条码管理WMS系统

物料档案条码添加和蓝牙条码标签打印,金蝶安卓盘点机PDA https://member.bilibili.com/platform/upload-manager/article 本期视频我们来讲解一下汉点机PDA条码添加和条码标签蓝牙便携打印: 在实际使用中,我们商品有两种情况: 一种是商品本身就有条码, 比如:超市卖的可口可乐,牛奶等商品,商品本身就有69开头的国标码,那么我们就可以使用盘点