forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0155-min-stack.js
102 lines (89 loc) · 2.18 KB
/
0155-min-stack.js
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
98
99
100
101
102
/**
* https://leetcode.com/problems/min-stack
* Time O(1) | Space O(N)
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/
class MinStack {
/**
* @constructor
*/
constructor () {
this.stack = [];
this.minStack = [];
}
/**
* @param {number} val
* @return {void}
*/
push (val, { minStack } = this) {
this.stack.push(val); /* Space O(N) */
const isMinEmpty = !minStack.length;
const hasNewMin = val <= this.top(minStack);
const canAddMin = isMinEmpty || hasNewMin;
if (canAddMin) minStack.push(val);/* Space O(N) */
}
/**
* @return {void}
*/
pop ({ stack, minStack } = this) {
const top = stack.pop(); /* Time O(1) */
const canPopMin = top === this.getMin();
if (canPopMin) minStack.pop(); /* Time O(1) */
}
/**
* @param {Array}
* @return {number}
*/
top (stack = this.stack) {
return stack.length
? stack[stack.length - 1] /* Time O(1) */
: null;
}
/**
* @return {number}
*/
getMin (minStack = this.minStack) {
return this.top(minStack); /* Time O(1) */
}
}
/**
* https://leetcode.com/problems/min-stack
* Time O(1) | Space O(1)
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/
class MinStack {
constructor () {
this.head = null
}
push (val) {
this.head = (!this.head) /* Space O(1) */
? new Node(val, val, null)
: new Node(val, Math.min(val, this.head.min), this.head);
}
pop () {
this.head = this.head.next;/* Time O(1) */
}
top () {
return this.head.val; /* Time O(1) */
}
getMin () {
return this.head.min; /* Time O(1) */
}
}
class Node {
constructor (val, min, next) {
this.val = val;
this.min = min;
this.next = next;
}
}