LeetCode-Easy刷题(33) Min Stack
Posted 当以乐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-Easy刷题(33) 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.
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.
创建一个栈对象,实现相应的方法.
public class MinStack
private int top = 0;
private int[] stack;
private int[] minStack;
private int minTop=-1;
/** initialize your data structure here. */
public MinStack()
stack = new int[8];
minStack = new int[8];
public void push(int x)
stack[top] = x;
if(minTop <0 ||minStack[minTop] >=x)
minTop++;
minStack[minTop] = x;
if(minTop>=minStack.length-1)
int[] newStack = new int[top*2];
for (int i = 0; i < minStack.length; i++)
newStack[i] = minStack[i];
minStack = newStack;
top++;
if(top >=stack.length)
int[] newStack = new int[top*2];
for (int i = 0; i < stack.length; i++)
newStack[i] = stack[i];
stack = newStack;
public void pop()
int remove = stack[top-1];
stack[top-1]=0;
top--;
if(remove ==minStack[minTop])
minStack[minTop] = 0;
minTop--;
public int top()
return stack[top-1];
public int getMin()
return minStack[minTop];
以上是关于LeetCode-Easy刷题(33) Min Stack的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode-Easy刷题(12) Length of Last Word
LeetCode-Easy刷题 Valid Parentheses
LeetCode-Easy刷题(31) Single Number