[LeetCode] Flatten Nested List Iterator

Given a nested list of integers, implement an iterator to flatten it.

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的迭代器进行遍历。

实现代码

// Runtime: 6 ms
/**
 * // 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();
 */
时间: 2024-11-01 15:27:04

[LeetCode] Flatten Nested List Iterator的相关文章

LeetCode All in One 题目讲解汇总(持续更新中...)

终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通过OJ,或是有更好的解法,或是有任何疑问,意见和建议的话,请一定要在对应的帖子下面评论区留言告知博主啊,多谢多谢,祝大家刷得愉快,刷得精彩,刷出美好未来- 博主制作了一款iOS的应用"Leetcode Meet Me",里面有Leetcode上所有的题目,并且贴上了博主的解法,随时随地都能

python基础学习笔记(十一)

迭代器   本节进行迭代器的讨论.只讨论一个特殊方法---- __iter__  ,这个方法是迭代器规则的基础.   迭代器规则 迭代的意思是重复做一些事很多次---就像在循环中做的那样.__iter__ 方法返回一个迭代器,所谓迭代器就是具有next方法的对象,在调用next方法时,迭代器会返回它的下一个值.如果next方法被调用,但迭代器没有值可以返回,就会引发一个StopIteration异常.   这里是一个婓波那契数例,使用迭代器如下: class Fibs: def __init__

python生成器的使用方法_python

什么是生成器?生成器是一个包含了特殊关键字yield的函数.当被调用的时候,生成器函数返回一个生成器.可以使用send,throw,close方法让生成器和外界交互. 生成器也是迭代器,但是它不仅仅是迭代器,拥有next方法并且行为和迭代器完全相同.所以生成器也可以用于python的循环中, 生成器如何使用? 首先看一个例子: 复制代码 代码如下: #!/usr/bin/python# -*- coding: utf-8 -*- def flatten(nested):    for subli

python 魔术函数调用的例子

场景 实现一个python调用java接口的功能,java接口是以http方式提供的.为了实现比较舒服的调用的方式,我不准备以send({"method": "echo"})这种方式调用,而是api.echo() 但是python里面并没有提供类似php的__call和__callStatic的函数 根据python的__getattr__来实现一个,但是这个解决方案不完美,有局限性. 实现  代码如下 复制代码 # encoding: utf-8 import j

[LeetCode]173.Binary Search Tree Iterator

[题目] Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and

[LeetCode]114.Flatten Binary Tree to Linked List

[题目] Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 [分析] 在先序遍历的过程中把二叉树转为链表. 用pre记住当前节点的前一节点.节点的右指针作为链表指针,同时左指针赋空(第一次wrong就是因为没赋空). pre->ri

【LeetCode从零单排】No 114 Flatten Binary Tree to Linked List

题目 Given a binary tree, flatten it to a linked list in-place. For example,Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 解题思路:利用递归找到倒数第一个父节点,记录下它的右节点,将左边的移到右边,然后再把之前标记的右节点连接上. 代码 public class Solution { public

[LeetCode] Peeking Iterator

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation – it essentially peek() at the element that will be returned by the next call to next(). Here is an example

JavaScript Array Flatten 与递归使用介绍_javascript技巧

如何用 JavaScript 将 [1,2,3,[4,5, [6,7]], [[[8]]]] 这样一个 Array 变成 [1,2,3,4,5, 6,7,8] 呢?传说中的 Array Flatten. 处理这种问题,通常我们会需要递归,来让程序自己按照一种算法去循环.在某书说写着,"递归是一种强大的编程技术",好吧,她不仅仅属于 JavaScript.递归可以很难,也可以比较简单(总得来说还是比较难).处理上面这个问题,用递归来解决,应该是比较适合的.之前工友这样实现了,算是一个简单