【Lintcode】528. Flatten Nested List Iterator

题目地址:

https://www.lintcode.com/problem/flatten-nested-list-iterator/description

给定一个嵌套整数的类,这个类要么是个整数,要么是个嵌套整数组成的列表。要求设计其迭代器,迭代其平铺开来后的所有整数。

思路是用栈,用类似于先序遍历多叉树的办法。初始化的时候先将nestedList逆序入栈。调用hasNext的时候,先判断一下栈顶是否是个整数;如果是,则返回true,否则将其pop出来,并且将pop出来的nestedList的NestedInteger逆序进栈;如此循环,直到栈顶是整数为止。如果栈最后变空了,说明没有整数了,返回false。也就是说,一旦调用hasNext,就要将下一个是整数的NestedInteger置于栈顶。调用next的时候直接pop掉栈顶返回即可。代码如下:

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;

public class NestedIterator implements Iterator<Integer> {
    
    private Deque<NestedInteger> stack;
    
    public NestedIterator(List<NestedInteger> nestedList) {
        // Initialize your data structure here.
        // 初始化一个栈,逆序将nestedList里的元素入栈
        stack = new ArrayDeque<>();
        for (int i = nestedList.size() - 1; i >= 0; i--) {
            stack.push(nestedList.get(i));
        }
    }
    
    // @return {int} the next element in the iteration
    @Override
    public Integer next() {
        // Write your code here
        return stack.pop().getInteger();
    }
    
    // @return {boolean} true if the iteration has more element or false
    @Override
    public boolean hasNext() {
        // Write your code here
        while (!stack.isEmpty()) {
        	// 看一下栈顶是否是整数,如果是,则返回true
            NestedInteger top = stack.peek();
            if (top.isInteger()) {
                return true;
            }
    		
    		// 否则将栈顶弹出,并将它含的NestedInteger逆序入栈
            stack.pop();
            for (int i = top.getList().size() - 1; i >= 0; i--) {
                stack.push(top.getList().get(i));
            }
        }
        
        // 栈空了,说明没有下一个整数了,返回false
        return false;
    }
    
    @Override
    public void remove() {
        stack.pop();
    }
}

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();
}

hasNext时间复杂度 O ( h ) O(h) O(h),next O ( 1 ) O(1) O(1) h h h是树高)。空间复杂度 O ( h ) O(h) O(h)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值