- 問題描述
定義棧的數據結構,請在該類型中實現一個能夠得到棧中所含最小元素的min函數(時間複雜度應爲O(1))。
- 解決方案1
利用一個輔助棧來存儲最小值,入棧和出棧時同時維護輔助棧,代碼如下:
import java.util.Stack;
public class Solution {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> helpStack = new Stack<Integer>();
public void push(int node) {
stack.push(node);
if(helpStack.isEmpty() || helpStack.peek() > node)
helpStack.push(node);
}
public void pop() {
int node = stack.pop();
if(node == helpStack.peek() && (stack.isEmpty() || node != stack.peek()))
helpStack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return helpStack.peek();
}
}
- 解決方案2
不用輔助棧來做,設定一個變量來保存最小值min,入棧時壓入元素node-min,如果壓入的元素小於最小值min,則將最小值更新爲node;
彈出元素時,如果彈出的元素爲負數,則將最小值更新爲min - node。代碼如下:
import java.util.Stack;
public class Solution {
Stack<Integer> stack = new Stack<>();
Integer min = null;
public void push(int node) {
if(min == null){
min = node;
stack.push(0);
}
else{
stack.push(node - min);
if(node < min)
min = node;
}
}
public void pop() {
int node = stack.pop();
if(node < 0)
min = min - node;
}
public int top() {
int node = stack.peek();
if(node < 0)
return min;
else
return node + min;
}
public int min() {
return min;
}
}