您的位置:首页 > 职场人生

LeetCode(64)- Min Stack

2016-04-18 23:05 274 查看

题目:

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.


思路:

题意:给出四个函数API,构造一个stack,而且能够返回最小值

用双栈的策略,一个用来正常的存储,一个用来存贮最小值

注意比较的时候。peek()函数要用equals函数比较,因为弹出的是对象

代码:

class MinStack {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> min = new Stack<Integer>();
public void push(int x) {
if(min.isEmpty() || x <= min.peek()){
min.push(x);
}
stack.push(x);
}

public void pop() {
if(stack == null){
return;
}
if(min.peek().equals(stack.peek())){
min.pop();
}
stack.pop();
}

public int top() {
return stack.peek();
}

public int getMin() {
return min.peek();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息