[leetcode/lintcode 题解]国内大厂面试真题详解:摊平二维向量

描述
设计一个迭代器来实现摊平二维向量的功能

在线评测地址:领扣题库官网

样例1
输入:[[1,2],[3],[4,5,6]]
输出:[1,2,3,4,5,6]
样例2
输入:[[7,9],[5]]
输出:[7,9,5]

解题思路
使用2个栈的算法解决Flatten 2D Vector 课堂所讲解的算法

源代码

public class Vector2D implements Iterator<Integer> {
    Stack<List<Integer>> stack = new Stack<>();
    Stack<Integer> stackj;
    
    void pushListListToStack(List<List<Integer>> vec2d) {
    Stack<List<Integer>> temp = new Stack<>();
        for (List<Integer> nested : vec2d) {
            temp.push(nested);
        }
        
        while (!temp.isEmpty()) {
            stack.push(temp.pop());
        }
    }
    
    void pushListToStack(List<Integer> vec) {
    Stack<Integer> temp = new Stack<>();
        for (Integer nested : vec) {
            temp.push(nested);
        }
        
        while (!temp.isEmpty()) {
            stackj.push(temp.pop());
        }
    }
    
    public Vector2D(List<List<Integer>> vec2d) {
        pushListListToStack(vec2d);
        // Initialize your data structure here
        stackj = new Stack<>();
    }

    public Integer next() {
        // Write your code here
        if(!hasNext()) {
            return null;
        }
        return stackj.pop();
    }

    public boolean hasNext() { // 准备下一个元素
        // Write your code here
        while (stackj.isEmpty() && !stack.isEmpty())
            pushListToStack(stack.pop());
        return !stackj.isEmpty();
    }
    
    public void remove() {}
}

更多题解参考:九章官网solution

上一篇:如何设计爬虫系统?


下一篇:[leetcode/lintcode 题解]算法面试真题详解:二叉搜索树结点最小距离