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

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

LeetCode 155.Min Stack

2019-11-08 03:04:39
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

description: 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. Example: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); –> Returns -3. minStack.pop(); minStack.top(); –> Returns 0. minStack.getMin(); –> Returns -2.

題目不難,可以直接使用java中給定的stack數(shù)據(jù)結(jié)構(gòu)進(jìn)行計(jì)算。但是要進(jìn)行記錄最小值元素就應(yīng)該使用另外的一個(gè)stack進(jìn)行處理。當(dāng)程序使用pop運(yùn)算時(shí),stack和minstack如果是排出的同一個(gè)元素則應(yīng)該將該元素從兩個(gè)stack中同時(shí)排除。 update: 有人問(wèn)我,為什么push方法中要使用equals方法,而不能使用 ==,因?yàn)镮nteger是引用類(lèi)型的數(shù)據(jù),引用類(lèi)型的數(shù)據(jù) == 表示指向同一個(gè)地址,而非表示值相同。

public class MinStack { PRivate Stack<Integer> stack; private Stack<Integer> minStack; /** initialize your data structure here. */ public MinStack() { stack = new Stack<Integer>(); minStack = new Stack<Integer>(); } public void push(int x) { stack.push(x); if (minStack.isEmpty()) { minStack.push(x); } else if (minStack.peek() >= x) { minStack.push(x); } } public void pop() { if (stack.peek().equals(minStack.peek())) { minStack.pop(); } stack.pop(); } public int top() { return stack.peek(); } public int getMin() { return minStack.peek(); }}/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 涪陵区| 金川县| 邯郸县| 天祝| 台前县| 星子县| 临朐县| 黑河市| 盖州市| 延庆县| 宁都县| 柳河县| 泰和县| 仙居县| 霍邱县| 丰城市| 望都县| 灵寿县| 加查县| 雅安市| 孝感市| 武乡县| 龙口市| 哈巴河县| 兴仁县| 江达县| 桃源县| 额济纳旗| 开原市| 中牟县| 宕昌县| 吉木乃县| 新余市| 阳谷县| 宁国市| 法库县| 宝坻区| 诏安县| 天峨县| 黄平县| 沅江市|