天天看點

[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

繼續閱讀