-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMinStack
More file actions
80 lines (70 loc) · 1.98 KB
/
Copy pathMinStack
File metadata and controls
80 lines (70 loc) · 1.98 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.striner.java.jzOffer;
import java.util.Stack;
public class MinStack33 {
private Stack<Integer> minStack;
private Stack<Integer> dataStack;
/**
* initialize your data structure here.
*/
public MinStack33() {
minStack = new Stack<>();
dataStack = new Stack<>();
}
//剑指 Offer 30. 包含min函数的栈
//定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
//
//
//
//示例:
//
//MinStack minStack = new MinStack();
//minStack.push(-2);
//minStack.push(0);
//minStack.push(-3);
//minStack.min(); --> 返回 -3.
//minStack.pop();
//minStack.top(); --> 返回 0.
//minStack.min(); --> 返回 -2.
//
//
//提示:
//
//各函数的调用总次数不超过 20000 次
//
//
//注意:本题与主站 155 题相同:https://leetcode-cn.com/problems/min-stack/
//https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
public static void main(String[] args) {
}
public void push(int x) {
dataStack.push(x);
if (minStack.empty()) {
minStack.push(x);
} else if (x <= minStack.peek()) {
minStack.push(x);
}
}
public void pop() {
Integer pop = dataStack.pop();
if(pop.equals(minStack.peek())) {
minStack.pop();
}
}
public int top() {
return dataStack.peek();
}
public int min() {
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.min();
*/
//执行结果: 通过
//执行用时: 18 ms , 在所有 Java 提交中击败了 94.63% 的用户
//内存消耗: 40.2 MB , 在所有 Java 提交中击败了 31.97% 的用户