LeetCode[stack]: 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.

Discuss上的这个解法:https://oj.leetcode.com/discuss/15679/share-my-java-solution-with-only-one-stack 非常巧妙,算法的关键在于用一个stack保存了当前元素与最小元素的差。为了避免Integer.MAXVALUE-Integer.MINVALUE这个异常出现,,采用Long类型来保存。Java代码如下:

public class MinStack {long min;Stack<Long> stack;public MinStack(){stack=new Stack<>();}(int x) {if (stack.isEmpty()){stack.push(0L);min=x;}else{stack.push(x-min);//Could be negative if min value needs to changeif (x<min) min=x;}}() {if (stack.isEmpty()) return;long pop=stack.pop();if (pop<0) min=min-pop;//If negative, increase the min value}() {long top=stack.peek();if (top>0){return (int)(top+min);}else{return (int)(min);}}() {return (int)min;}}

这个算法的时间性能如下:

但是我在用C++实现相同的算法时却得到“Memory Limit Exceeded”,这是因为当用long类型时,其实无异于用两个stack。尽管如此,这个算法的思想还是值得学习的。

莫找借口失败,只找理由成功。(不为失败找理由,要为成功找方法)

LeetCode[stack]: Min Stack

相关文章:

你感兴趣的文章:

标签云: