最小栈JAVA实现_LeetCode简单题:155. 最小栈(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/min-stack/

要点:辅助栈

Python,C++,Java都用了相同的辅助栈法,顾名思义就是有个栈放在原来栈旁边执行相关的操作,使得每个元素 a 与其相应的最小值 m 时刻保持一一对应。因此我们可以使用一个辅助栈,与元素栈同步插入与删除,用于存储与每个元素对应的最小值。

二.Python实现

class MinStack:

def __init__(self):

self.stack = []

self.min_stack = [math.inf]

def push(self, x: int) -> None:

self.stack.append(x)

self.min_stack.append(min(x, self.min_stack[-1]))

def pop(self) -> None:

self.stack.pop()

self.min_stack.pop()

def top(self) -> int:

return self.stack[-1]

def getMin(self) -> int:

return self.min_stack[-1]

# Your MinStack object will be instantiated and called as such:

# obj = MinStack()

# obj.push(x)

# obj.pop()

# param_3 = obj.top()

# param_4 = obj.getMin()

三.C++实现

class MinStack {

public:

/** initialize your data structure here. */

MinStack() {

}

stack a;

stack min;

void push(int x) {

a.push(x);

if(min.empty()||x<=min.top()) min.push(x);

}

void pop() {

if(a.top()==min.top()) min.pop();

a.pop();

}

int top() {

return a.top();

}

int getMin() {

return min.top();

}

};

/**

* Your MinStack object will be instantiated and called as such:

* MinStack* obj = new MinStack();

* obj->push(x);

* obj->pop();

* int param_3 = obj->top();

* int param_4 = obj->getMin();

*/

四.java实现

class MinStack {

private Stack stack;

private Stack min_stack;

public MinStack() {

stack = new Stack<>();

min_stack = new Stack<>();

}

public void push(int x) {

stack.push(x);

if(min_stack.isEmpty() || x <= min_stack.peek())

min_stack.push(x);

}

public void pop() {

if(stack.pop().equals(min_stack.peek()))

min_stack.pop();

}

public int top() {

return stack.peek();

}

public int getMin() {

return min_stack.peek();

}

}

/**

* Your MinStack object will be instantiated and called as such:

* MinStack obj = new MinStack();

* obj.push(x);

* obj.pop();

* int param_3 = obj.top();

* int param_4 = obj.getMin();

*/

你可能感兴趣的:(最小栈JAVA实现)