日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

【LeetCode笔记】232. 用栈实现队列(Java、栈、队列)

發布時間:2024/7/23 java 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode笔记】232. 用栈实现队列(Java、栈、队列) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目描述

  • 經典題了,貌似現在面試也有點喜歡問,今天補補題!
  • 要實現均攤時間復雜度O(1)噢

思路 & 代碼

  • 用兩個棧來實現:輸出棧 & 輸入棧
  • 輸出棧 out:負責 pop、peek
  • 輸入棧 in:負責 push
  • 關鍵點:in.size() + out.size() == MyQueue.size(),也就是隊列元素分布在兩個棧中
  • peek & pop:會有一個倒棧處理,把 in 的內容全倒入 out 中。
/*** 要點:in.size() + out.size() == MyQueue.size() */class MyQueue {Stack<Integer> in;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);}/** Removes the element from in front of queue and returns that element. */public int pop() {// 出棧空,入棧導入if(out.isEmpty()){while(!in.isEmpty()){out.push(in.pop());}}return out.pop();}/** Get the front element. */public int peek() {if(out.isEmpty()){while(!in.isEmpty()){out.push(in.pop());}}return out.peek();}/** Returns whether the queue is empty. */public boolean empty() {return in.isEmpty() && out.isEmpty();} }/*** Your MyQueue object will be instantiated and called as such:* MyQueue obj = new MyQueue();* obj.push(x);* int param_2 = obj.pop();* int param_3 = obj.peek();* boolean param_4 = obj.empty();*/

更新版

  • 換成 ArrayDeque()
class MyQueue {ArrayDeque<Integer> in;ArrayDeque<Integer> out;public MyQueue() {in = new ArrayDeque<>();out = new ArrayDeque<>();}public void push(int x) {in.push(x);}public int pop() {if(out.isEmpty()) {while(!in.isEmpty()) {out.push(in.pop());}}return out.pop();}public int peek() {if(out.isEmpty()) {while(!in.isEmpty()) {out.push(in.pop());}}return out.peek();}public boolean empty() {return in.isEmpty() && out.isEmpty();} }

總結

以上是生活随笔為你收集整理的【LeetCode笔记】232. 用栈实现队列(Java、栈、队列)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。