刷题

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

一、题目描述:

给你一个嵌套的整数列表 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] 内

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/flatten-nested-list-iterator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、思路分析:

首先在构造函数中便通过递归的方法直接将Nested类型的列表转换为Integer类型的列表(递归抽取NestedList中的所有Integer);
然后再通过简单的迭代器模式对Integer类型的列表进行迭代。

三、AC 代码:

public class NestedIterator implements Iterator<Integer> {
    private int index = 0;
    private List<Integer> valList;

    public NestedIterator(List<NestedInteger> nestedList) {
        valList = new ArrayList<>();    ////初始化一个Integer列表
        getVal(nestedList);             //对Nested列表进行递归。
    }

    @Override
    public Integer next() {
        index++;
        return valList.get(index - 1);
    }

    public void getVal(List<NestedInteger> nesteds){
        int listIndex = 0;
        while(listIndex < nesteds.size()){
            if(nesteds.get(listIndex).isInteger()){
                valList.add(nesteds.get(listIndex).getInteger());
            }else{
                getVal(nesteds.get(listIndex).getList());
            }
            listIndex++;
        }
    }

    @Override
    public boolean hasNext() {
        if(index < valList.size()){
            return true;
        }else{
            return false;
        }
    }
}

相关文章
|
4天前
leetcode24刷题打卡
leetcode24刷题打卡
13 0
|
4天前
|
索引
刷题之Leetcode35题(超级详细)
刷题之Leetcode35题(超级详细)
15 0
|
4天前
|
算法
刷题之Leetcode34题(超级详细)
刷题之Leetcode34题(超级详细)
12 0
|
4天前
|
索引
刷题之Leetcode707题(超级详细)
刷题之Leetcode707题(超级详细)
14 0
|
4天前
刷题之Leetcode206题(超级详细)
刷题之Leetcode206题(超级详细)
23 0
刷题之Leetcode206题(超级详细)
|
4天前
|
索引
leetcode151刷题打卡
leetcode151刷题打卡
18 0
|
12月前
|
Java 测试技术 C语言
leetcode刷题(5)
各位朋友们,大家好,今天是我leedcode刷题的第五篇,我们一起来看看吧。
|
算法 测试技术 C++
|
存储 算法