文章最前: 我是Octopus,这个名字来源于我的中文名--章鱼;我热爱编程、热爱算法、热爱开源。所有源码在我的个人github ;这博客是记录我学习的点点滴滴,如果您对 Python、Java、AI、算法有兴趣,可以关注我的动态,一起学习,共同进步。
相关文章:
- LeetCode:55. Jump Game(跳远比赛)
- Leetcode:300. Longest Increasing Subsequence(最大增长序列)
- LeetCode:560. Subarray Sum Equals K(找出数组中连续子串和等于k)
文章目录:
题目描述:
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
来源:力扣(LeetCode)
java实现方法1:
利用栈的形式,这个比较好想到,也是比较习惯的方式
public class MinStack {
private Deque<Integer> stack = null;
public MinStack() {
stack = new ArrayDeque<>();
}
public void push(int x) {
stack.push(x);
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return stack.stream().mapToInt(e -> e.intValue()).min().getAsInt();
}
}
时间复杂度:O(n)
空间复杂度:O(1)
python实现方式1:
class MinStack:
stack = []
def push(self, x: int) -> None:
'''
元素压入栈中
Args:
x: 元素
Returns:
None
'''
self.stack.append(x)
def pop(self) -> None:
'''
弹出一个元素
Returns:
None
'''
self.stack.pop()
def top(self) -> int:
'''
弹出栈顶元素
Returns:
栈顶元素
'''
return self.stack[-1]
def get_min(self) -> int:
'''
获取一个最小值
Returns:
最小值
'''
return min(self.stack)
时间复杂度:O(n)
空间复杂度:O(1)
java实现方法2:
利用链表的形式,维护着栈的平衡
class MinStack {
private int min = Integer.MAX_VALUE;
private Node head;
public class Node {
int val;
Node next;
public Node(){}
public Node(int val) {
this.val = val;
}
}
public MinStack() {
}
public void push(int x) {
if (head == null) {
head = new Node(x);
} else {
Node n = new Node(x);
n.next = head;
head = n;
}
if (x < min) {
min = x;
}
}
public void pop() {
if (head != null) {
head = head.next;
min = Integer.MAX_VALUE;
Node cur = head;
while (cur != null) {
if (cur.val < min) {
min = cur.val;
}
cur = cur.next;
}
}
}
public int top() {
return head.val;
}
public int getMin() {
return min;
}
}
时间复杂度:O(n)
空间复杂度:O(n)
python实现方式2:
class MinStack:
min_num = sys.maxsize
head = None
class Node:
val = None
next_node = None
def __init__(self, val: int):
self.val = val
def push(self, x: int) -> None:
'''
元素压入栈中
Args:
x: 元素
Returns:
None
'''
if not self.head:
self.head = self.Node(x)
else:
n = self.Node(x)
n.next_node = self.head
self.head = n
if x < self.min_num:
self.min_num = x
def pop(self) -> None:
'''
弹出一个元素
Returns:
None
'''
if not self.head:
self.head = self.head.next_node
self.min_num = sys.maxsize
cur = self.head
while cur:
if cur.val<self.min_num:
self.min_num=cur.val
cur=cur.next_node
def top(self) -> int:
'''
弹出栈顶元素
Returns:
栈顶元素
'''
return self.stack[-1]
def get_min(self) -> int:
'''
获取一个最小值
Returns:
最小值
'''
return self.min_num
时间复杂度:O(n)
空间复杂度:O(n)