/
Solution.java
executable file
·97 lines (76 loc) · 1.67 KB
/
Solution.java
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.util.LinkedList;
class MinStack {
int min_value = Integer.MIN_VALUE;
LinkedList<Integer> stack = new LinkedList<>();
public void push(int x) {
if(x < min_value){
min_value = x;
}
stack.push(min_value);
stack.push(x);
}
public void pop() {
if(!stack.isEmpty()) {
stack.pop();
stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
if(stack.size()>=2)
return stack.get(1);
return 0;
}
}
class MinStack {
static class Stack {
static class Node {
int val;
Node next;
Node prev;
}
Node head = new Node();
int size = 0;
public void push(int x) {
Node n = new Node();
n.val = x;
n.prev = head;
head.next = n;
head = n;
size++;
}
public void pop() {
head = head.prev;
size--;
}
public int top() {
return head.val;
}
}
Stack data = new Stack();
Stack mins = new Stack();
public void push(int x) {
data.push(x);
if(mins.size == 0 || getMin() >= x){
mins.push(x);
}
}
public void pop() {
int last = data.top();
data.pop();
if(last <= getMin()){
mins.pop();
}
}
public int top() {
return data.top();
}
public int getMin() {
if(mins.size > 0){
return mins.top();
}
throw new IllegalStateException();
}
}