leetcode155. 最小栈
生活随笔
收集整理的這篇文章主要介紹了
leetcode155. 最小栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
設計一個支持 push,pop,top 操作,并能在常數時間內檢索到最小元素的棧。
push(x)?-- 將元素 x 推入棧中。
pop()?-- 刪除棧頂的元素。
top()?-- 獲取棧頂元素。
getMin() -- 檢索棧中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); ? --> 返回 -3.
minStack.pop();
minStack.top(); ? ? ?--> 返回 0.
minStack.getMin(); ? --> 返回 -2.
思路:輔助棧。跟著主棧壓和彈,但是壓入的是當前最小值。取最小值時就取輔助棧的棧頂即可。
import java.util.Stack;public class MinStack {// 數據棧private Stack<Integer> data;// 輔助棧private Stack<Integer> helper;/*** initialize your data structure here.*/public MinStack() {data = new Stack<>();helper = new Stack<>();}public void push(int x) {data.add(x);if (helper.isEmpty() || helper.peek() >= x) {helper.add(x);} else {helper.add(helper.peek());}}public void pop() {helper.pop();data.pop();}public int top() {return data.peek();}public int getMin() {return helper.peek();} }?
總結
以上是生活随笔為你收集整理的leetcode155. 最小栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线性表表示集合
- 下一篇: leetcode268. 缺失数字