LeetCode232之用棧實現佇列(Implement Queue using Stacks)
阿新 • • 發佈:2018-11-04
一、題目
二、一種解題思路
1)介紹:雙棧實現佇列法
方法解析:使用兩個棧做為基礎,一個棧儲存輸入的元素,另外一個棧將前面棧中的元素儲存到自己中,這樣就實現了佇列的效果,最先進的元素在in棧的棧底,out棧的棧頂。 ()從一個棧到另外一個棧的操作,僅在out棧為empty時進行,也就是實現了佇列的先進先出)。
時間複雜度:O(n)
空間複雜度:O(n)
2)核心程式碼:
public class MyQueue { //兩個輔助棧 private Stack<Integer> in; private Stack<Integer> out; /** * Initialize your data structure here. */ public MyQueue() { in = new Stack<>(); out = new Stack<>(); } /** * Push element x to the back of queue. */ public void push(int x) { in.push(x); } private void repair() { while (!in.empty()) { out.push(in.pop()); } } /** * Removes the element from in front of queue and returns that element. */ public int pop() { if (out.empty()) { repair(); } return out.pop(); } /** * Get the front element. */ public int peek() { while (out.empty()) { repair(); } return out.peek(); } /** * Returns whether the queue is empty. */ public boolean empty() { return in.isEmpty() && out.isEmpty(); } }
三、LeetCode成功截圖
四、感想
感覺自己還沒做到最好,希望大家有好方法指教下,加油,加油,再加油,堅持,堅持,再堅持。