Leetcode 341. 扁平化嵌套列表迭代器(中等)
题目:
首先,现在有一种数据结构 NestedInteger
,这个结构中存的数据可能是一个 Integer
整数,也可能是一个 NestedInteger
列表。注意,这个列表里面装着的是 NestedInteger
,也就是说这个列表中的每一个元素可能是个整数,可能又是个列表,这样无限递归嵌套下去……
NestedInteger
有如下 API:
/** * // 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; * }; */
我们的算法会被输入一个 NestedInteger
列表,我们需要做的就是写一个迭代器类,将这个带有嵌套结构 NestedInteger
的列表「拍平」:
* NestedIterator(List<NestedInteger> nestedList) 用嵌套列表 nestedList 初始化迭代器。
* int next() 返回嵌套列表的下一个整数。
* boolean hasNext() 如果仍然存在待迭代的整数,返回 true ;否则,返回 false 。
我们写的这个类会被这样调用,先调用
hasNext
方法,后调用 next
方法:* initialize iterator with nestedList * res = [] * while iterator.hasNext() * append iterator.next() to the end of res * return res
思路:
使用递归的方法来把这个具有list的列表展平,然后逐次遍历就可以
class NestedIterator { public: NestedIterator(vector<NestedInteger> &nestedList) { flatten(nestedList); idx_=0; } void flatten(vector<NestedInteger> &nestedList){ for(auto& i:nestedList){ if(i.isInteger()){ data_.push_back(i.getInteger()); }else{ flatten(i.getList()); } } } int next() { return data_[idx_++]; } bool hasNext() { return idx_<data_.size(); } private: vector<int> data_; int idx_; };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
分类:
leetcode
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库