您的位置:首页 > 其它

[LeetCode]155. Min Stack

2016-03-06 10:09 288 查看

Problem 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.

[]https://leetcode.com/problems/min-stack/]

思路

TLE版:维护两个LinkedList,一个按顺序排列,一个按栈排列。插入时用二分查找找位置。

大神版:栈里保存an=bn-min{an-1……….0};bn是真正压栈的数。

[]https://leetcode.com/discuss/15679/share-my-java-solution-with-only-one-stack]

Code

package q155;

import java.util.Stack;

public class MinStack {

private static Stack<Long> s;

public MinStack() {
s = new Stack<Long>();
}

private static long min = (long) Integer.MIN_VALUE;

public static void push(int x) {
if (s.isEmpty()) {
min = (long) x;
s.push(0L);
} else {
if (min >= x) {
s.push(x - min);
min = (long) x;
} else {
s.push(x - min);
}
}
}

public static void pop() {
if (!s.isEmpty()) {
long tmp = s.pop();
if (tmp < 0)
min = min - tmp;
}

}

public static int top() {
if (!s.isEmpty()) {
long tmp = s.peek();
if (tmp > 0)
return (int) (min + tmp);
else
return (int) (min);
}
return -1;
}

public static int getMin() {
return (int) min;
}

//  public static void main(String[] args) {
//
//      MinStack.push(-1);
//      System.out.print(MinStack.top());
//      System.out.print(MinStack.getMin());
//  }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode