动态

详情 返回 返回

leetcode 232. Implement Queue using Stacks 用棧實現隊列(簡單) - 动态 详情

一、題目大意

標籤: 棧和隊列

https://leetcode.cn/problems/implement-queue-using-stacks

請你僅使用兩個棧實現先入先出隊列。隊列應當支持一般隊列支持的所有操作(push、pop、peek、empty):

實現 MyQueue 類:

void push(int x) 將元素 x 推到隊列的末尾
int pop() 從隊列的開頭移除並返回元素
int peek() 返回隊列開頭的元素
boolean empty() 如果隊列為空,返回 true ;否則,返回 false
説明:

你 只能 使用標準的棧操作 —— 也就是隻有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的語言也許不支持棧。你可以使用 list 或者 deque(雙端隊列)來模擬一個棧,只要是標準的棧操作即可。
 

示例 1:

輸入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 1, 1, false]

解釋:

MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

 

提示:

  • 1 <= x <= 9
  • 最多調用 100 次 push、pop、peek 和 empty
  • 假設所有操作都是有效的 (例如,一個空的隊列不會調用 pop 或者 peek 操作)

 

進階:
你能否實現每個操作均攤時間複雜度為 O(1) 的隊列?換句話説,執行 n 個操作的總時間複雜度為 O(n) ,即使其中一個操作可能花費較長時間。

二、解題思路

用兩個棧來實現一個隊列:因為需要得到先入先出的結果,所以必定要通過一個額外棧翻一次數組。這個翻轉過程既可以在插入時完成,也可以在取值時完成。

下面解決在插入時完成翻轉過程。

三、解題方法

3.1 Java實現

class MyQueue {

    Stack<Integer> stackA;
    Stack<Integer> stackB;

    public MyQueue() {
        stackA = new Stack<>();
        stackB = new Stack<>();
    }

    public void push(int x) {
        if (stackA.isEmpty()) {
            stackA.push(x);
            return;
        }
        while (!stackA.isEmpty()) {
            stackB.push(stackA.pop());
        }
        stackB.push(x);
        while (!stackB.isEmpty()) {
            stackA.push(stackB.pop());
        }
    }

    public int pop() {
        return stackA.pop();
    }

    public int peek() {
        return stackA.peek();
    }

    public boolean empty() {
        return stackA.isEmpty();
    }
}

四、總結小記

  • 2022/8/7 週末也要刷一題
user avatar moax 头像 liubo86 头像 huaweichenai 头像 wenroudemangguo 头像 hoistthecolorsandsteptotherail 头像 houbinbin 头像 yaochujiadebiandou 头像 yuelianggeimengnalisha 头像 fu_623f04ad34d53 头像
点赞 9 用户, 点赞了这篇动态!
点赞

Add a new 评论

Some HTML is okay.