-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinStack.java
72 lines (61 loc) · 1.14 KB
/
MinStack.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
/**
* @author Shogo Akiyama
* Solved on 12/04/2019
*
* 155. Min Stack
* https://leetcode.com/problems/min-stack/
* Difficulty: Easy
*
* Approach: Two Node Pointers
* Runtime: 4 ms, faster than 99.89% of Java online submissions for Min Stack.
* Memory Usage: 40.4 MB, less than 29.71% of Java online submissions for Min Stack.
*
* Time Complexity: O(n)
* Space Complexity: O(n)
* Where n is the number of elements in a stack
*
*/
public class MinStack {
private Node tail;
private Node min;
/** initialize your data structure here. */
public MinStack() {
tail = null;
min = null;
}
public void push(int x) {
Node newNode = new Node(x);
newNode.next = tail;
tail = newNode;
if (min == null) {
min = newNode;
} else if (x < min.val) {
newNode.minNext = min;
min = newNode;
}
}
public void pop() {
if (tail != null) {
if (tail == min) {
min = min.minNext;
}
tail = tail.next;
}
}
public int top() {
return tail.val;
}
public int getMin() {
return min.val;
}
class Node {
int val;
Node next;
Node minNext;
Node(int v) {
val = v;
next = null;
minNext = null;
}
}
}