zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[LeetCode] Flatten Nested List Iterator

LeetCodeList Iterator nested Flatten
2023-09-14 09:01:04 时间
Each element is either an integer, or a list – whose elements may also be integers or other lists. Example 1: Given

Each element is either an integer, or a list – whose elements may also be integers or other lists.

Example 1:
Given the list [[1,1],2,[1,1]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 2:
Given the list [1,[4,[6]]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

首先递归把integer元素集中到一个list中,然后再借助list的迭代器进行遍历。


* // 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 = new ArrayList (); private Iterator Integer iterator = null; public NestedIterator(List NestedInteger nestedList) { for (NestedInteger nestedInteger : nestedList) { addNestedInteger(nestedInteger); iterator = nums.iterator(); @Override public Integer next() { return iterator.next(); @Override public boolean hasNext() { return iterator.hasNext(); private void addNestedInteger(NestedInteger nestedInteger) { if (nestedInteger.isInteger()) { nums.add(nestedInteger.getInteger()); } else { List NestedInteger nestedList = nestedInteger.getList(); for (NestedInteger nested : nestedList) { addNestedInteger(nested); * Your NestedIterator object will be instantiated and called as such: * NestedIterator i = new NestedIterator(nestedList); * while (i.hasNext()) v[f()] = i.next(); */
LeetCode 341. Flatten Nested List Iterator 给定一个嵌套的整型列表。设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的项或者为一个整数,或者是另一个列表。
LeetCode 109. Convert Sorted List to BST 给定一个链表,其中元素按升序排序,将其转换为高度平衡的BST。 对于这个问题,高度平衡的二叉树被定义为:二叉树中每个节点的两个子树的深度从不相差超过1。
这个题目是在一个公司现场面谈的时候的一个题目。虽然对这种找工作上来就做题目的现象比较反感。 但是大环境如此,也只能被蹂躏了。 题目要求比较简单:[1,2,[3],[[4]],5,6] - [1,2,3,4,5,6] 就是数组中嵌套数组,考察一个数组[1,2,[3],[[4]],5,6]。