設計一個支持 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.
思路:
-
鏈式棧:
使用兩個鏈式棧stack,minStack ;stack正常的出棧和入棧;當stack入棧x的時候和minstack棧頂比較,如果入棧的值比minstack小,就把x在minstack中進行入棧,所以minstack保存的是較小的值;
出棧操作:stack出棧,使用棧頂元素與minstack棧頂值比較,如果大于minstack的棧頂值就可以判斷stack的最小值為minstack棧頂值;反之。
public class MinStack {
private Stack<int> stack = new Stack<int>();
private Stack<int> minStack = new Stack<int>();
/** initialize your data structure here. */
public MinStack() {
}
public void Push(int x) {
if (minStack.isEmpty() || x <= minStack.peek())
{
minStack.push(x);
}
stack.push(x);
}
public void Pop() {
if (stack.peek() == minStack.peek())
{
minStack.pop();
}
stack.pop();
}
public int Top() {
return stack.peek();
}
public int GetMin() {
return minStack.peek();
}
}
-
順序棧
思路與鏈式棧的相同:
private int[] s1, s2;
private int n = 10;// 棧的大小
private int count = 0;//長度
private int s2ount = 0;//長度
/** initialize your data structure here. */
public MinStack()
{
s1 = new int[n];
s2 = new int[n];
}
public void Push(int x)
{
if (n == count) return;
s1[count] = x;
if (s2ount == 0)
{
s2[0] = x;
++s2ount;
}
else
{
int valTop = s1[count - 1];
if (valTop > x)
{
s2[s2ount] = x;
s2ount++;
}
}
++count;
}
public void Pop()
{
if (count == 0) return;
int topval = s1[count - 1];
--count;
if (s2ount > 0 && topval <= s2[s2ount - 1])
{
-- s2ount;
}
}
public int Top()
{
if (count > 0) return s1[count - 1];
return -999;
}
public int GetMin()
{
if (s2ount > 0)
return s2[s2ount - 1];
return -999;
}