我是靠谱客的博主 健忘黑夜,这篇文章主要介绍LeetCode之最小栈,现在分享给大家,希望可以做个参考。

题目:
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) —— 将元素 x 推入栈中。
  • pop() —— 删除栈顶的元素。
  • top() —— 获取栈顶元素。
  • getMin() —— 检索栈中的最小元素
    示例:
    在这里插入图片描述
    方法:辅助栈
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class MinStack { //Deque:支持两端插入和移除的线性集合 Deque<Integer> xStack; Deque<Integer> minStack; /** initialize your data structure here. */ public MinStack() { this.minStack=new LinkedList<Integer>(); this.xStack=new LinkedList<Integer>(); minStack.push(Integer.MAX_VALUE); } public void push(int x) { xStack.push(x); minStack.push(Math.min(minStack.peek(),x)); } public void pop() { xStack.pop(); minStack.pop(); } public int top() { return xStack.peek(); } public int getMin() { return minStack.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(); */

最后

以上就是健忘黑夜最近收集整理的关于LeetCode之最小栈的全部内容,更多相关LeetCode之最小栈内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部