要求
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
解题
C++版本#includePython版本using namespace std; #include class MinStack { public: stack A; stack B; MinStack() {} void push(int x) { A.push(x); // 将x添加到栈A中 if (B.empty() || B.top() >= x) B.push(x); // 将x添加到栈B中 } void pop() { if (A.top() == B.top()) // 判断栈A栈顶元素是否与栈B栈顶元素相等 B.pop();// 栈B弹出栈顶元素 A.pop(); // 弹出栈A栈顶元素 } int top() { return A.top(); // 返回栈A栈顶元素 } int min() { return B.top(); // 返回栈B栈顶元素 } }; void test01() { MinStack m; m.push(0); m.push(3); m.push(-3); cout << m.min() << endl; m.pop(); cout << m.top() << endl; cout << m.min() << endl; } int main() { test01(); system("pause"); return 0; }
class MinStack:
def __init__(self):
self.A = []
self.B = []
def push(self, x):
self.A.append(x) # 将x添加到栈A中
if not self.B or self.B[-1] >= x:
self.B.append(x) # 将x添加到栈B中
def pop(self):
if self.A.pop() == self.B[-1]: # 判断栈A弹出元素是否与栈B栈顶元素相等
self.B.pop() # 栈B弹出栈顶元素
def top(self):
return self.A[-1] # 返回栈A栈顶元素
def min(self):
return self.B[-1] # 返回栈B栈顶元素
def test01():
minstack = MinStack()
minstack.push(0)
minstack.push(3)
minstack.push(-3)
print(minstack.min())
minstack.pop()
print(minstack.top())
print(minstack.min())
if __name__=="__main__":
test01()
Java版本
package com.hailei_01;
import java.util.Stack;
public class minStack {
public static void main(String[] args) {
MinStack C = new MinStack();
C.push(0);
C.push(3);
C.push(-3);
System.out.println(C.min());
C.pop();
System.out.println(C.top());
System.out.println(C.min());
}
public static class MinStack {
static Stack A;
static Stack B;
public MinStack() {
A = new Stack<>();
B = new Stack<>();
}
public static void push(int x) {
A.add(x); // 将x添加到栈A中
if(B.empty() || B.peek() >= x)
B.add(x); // 将x添加到栈B中
}
public static void pop() {
if(A.pop().equals(B.peek())) // 判断栈A弹出元素是否与栈B栈顶元素相等
B.pop(); // 栈B弹出栈顶元素
}
public static int top() {
return A.peek(); // 返回栈A栈顶元素
}
public static int min() {
return B.peek(); // 返回栈B栈顶元素
}
}
}
希望本文对大家有帮助,上文若有不妥之处,欢迎指正
分享决定高度,学习拉开差距



