2021.3.5每日一題

232. 用棧實(shí)現(xiàn)隊(duì)列

請(qǐng)你僅使用兩個(gè)棧實(shí)現(xiàn)先入先出隊(duì)列。隊(duì)列應(yīng)當(dāng)支持一般隊(duì)列的支持的所有操作(push、pop、peek、empty):

實(shí)現(xiàn) MyQueue 類:

void push(int x) 將元素 x 推到隊(duì)列的末尾
int pop() 從隊(duì)列的開(kāi)頭移除并返回元素
int peek() 返回隊(duì)列開(kāi)頭的元素
boolean empty() 如果隊(duì)列為空,返回 true ;否則,返回 false

說(shuō)明:

你只能使用標(biāo)準(zhǔn)的棧操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的語(yǔ)言也許不支持棧。你可以使用 list 或者 deque(雙端隊(duì)列)來(lái)模擬一個(gè)棧,只要是標(biāo)準(zhǔn)的棧操作即可。

進(jìn)階:

你能否實(shí)現(xiàn)每個(gè)操作均攤時(shí)間復(fù)雜度為 O(1) 的隊(duì)列?換句話說(shuō),執(zhí)行 n 個(gè)操作的總時(shí)間復(fù)雜度為 O(n) ,即使其中一個(gè)操作可能花費(fèi)較長(zhǎng)時(shí)間。

示例:

輸入:
["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

題解

可以把一個(gè)棧當(dāng)做「輸入?!梗蚜硪粋€(gè)棧當(dāng)做「輸出?!?。
當(dāng) push() 新元素的時(shí)候,放到「輸入?!沟臈m?,記此順序?yàn)椤篙斎胄颉埂?br> 當(dāng) pop() 元素的時(shí)候,是從「輸出?!箯棾鲈?。如果「輸出?!篂榭眨瑒t把「輸入?!沟脑刂饌€(gè) pop() 并且 push() 到「輸出棧」中,這一步會(huì)把「輸入棧」的棧底元素放到了「輸出?!沟臈m?。此時(shí)負(fù)負(fù)得正,從「輸出?!沟?pop() 元素的順序與「輸入序」相同。

   class MyQueue {
        private Deque<Integer> stack1;
        private Deque<Integer> stack2;

        /**
         * Initialize your data structure here.
         */
        public MyQueue() {
            stack1 = new ArrayDeque<>();
            stack2 = new ArrayDeque<>();
        }

        /**
         * Push element x to the back of queue.
         */
        public void push(int x) {
            stack1.addLast(x);
        }

        /**
         * Removes the element from in front of queue and returns that element.
         */
        public int pop() {
            if (stack2.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.addFirst(stack1.pollLast());
                }
            }
            return stack2.pollFirst();
        }

        /**
         * Get the front element.
         */
        public int peek() {
            if (stack2.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.addFirst(stack1.pollLast());
                }
            }
            return stack2.peekFirst();
        }

        /**
         * Returns whether the queue is empty.
         */
        public boolean empty() {
            return stack1.isEmpty() && stack2.isEmpty();
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容