国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

Leetcode: Min Stack

2019-11-14 21:59:20
字體:
供稿:網(wǎng)友
Leetcode: Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.push(x) -- Push element x onto stack.pop() -- Removes the element on top of the stack.top() -- Get the top element.getMin() -- Retrieve the minimum element in the stack.

這是一道關于棧的題目,整體來說比較簡單。我最開始想的時候想的太簡單,以為使用一個棧st, 再維護一個最小值變量就好了。突然發(fā)現(xiàn)pop()操作之后需要更新這個最小值,那就需要知道第二小的值,這個第二小的值怎么找呢?于是乎我想到了使用另外一個棧minst專門來存儲最小值。push()操作的時候每當x小于或等于(注意不是小于,之所以小于等于是為了元素重復的情況)minst的棧頂元素,minst也push x入棧。pop()操作時,如果pop出來的元素等于minst棧頂元素,那么minst棧也出棧。

這道題思路很簡單,到時語法卡了我一會兒,老是過不了,一段時間不練手生啊。我的語法問題又出在==跟equals()上面。我棧的定義是Stack<Integer>。Integer是一個object。那么判斷兩個棧棧頂元素相等就不能寫成 st.peek() == minst.peek(),這是地址相等,equals才是值相等。要改的話要么就改用equals,要么定義一個int elem = st.pop(); 再判斷if (elem == minst.peek()), 這里是一個int 變量跟Integer對象相比,而不是兩個Integer對象相比,==在這里就是表示值相等。

 1 class MinStack { 2     Stack<Integer> st; 3     Stack<Integer> minst; 4      5     public MinStack() { 6         this.st = new Stack<Integer>(); 7         this.minst = new Stack<Integer>(); 8     } 9     10     public void push(int x) {11         st.push(x);12         if (minst.empty() || minst.peek()>=x) {13             minst.push(x);14         }15     }16 17     public void pop() {18         if (st.isEmpty()) {19             return;20         }21         if (st.peek().equals(minst.peek())) {22             minst.pop();23         }24         st.pop();25     }26 27     public int top() {28         if (!st.isEmpty()) {29             return st.peek();30         }31         return Integer.MAX_VALUE;32     }33 34     public int getMin() {35         if (!minst.isEmpty()) {36             return minst.peek();37         }38         return Integer.MAX_VALUE;39     }40 }


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 陕西省| 延安市| 四子王旗| 南溪县| 开原市| 靖西县| 墨江| 和静县| 汉寿县| 油尖旺区| 峡江县| 漳州市| 阆中市| 赤水市| 石渠县| 海晏县| 家居| 安泽县| 贵德县| 长白| 白玉县| 临漳县| 淳化县| 恭城| 东台市| 堆龙德庆县| 维西| 酒泉市| 集贤县| 洞口县| 金川县| 昌江| 泸水县| 阿图什市| 增城市| 肥西县| 阿勒泰市| 邳州市| 神木县| 昆山市| 巢湖市|