-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathleetcode-155-MinStack.js
89 lines (78 loc) · 1.88 KB
/
leetcode-155-MinStack.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
// // stack [4,5,6,7,8,1,2,3]
// // minstack [4,1]
// class MinStack {
// constructor () {
// this.stack = [];
// this.minstack = [];
// }
// push (val) {
// // if minstack empty && val <= last index of minstack
// // => push minstack along with stack
// if (this.minstack.length === 0 || val < this.minstack[this.minstack.length - 1]) {
// this.minstack.push(val);
// }
// this.stack.push(val);
// }
// pop () {
// // pop minstack if last stack = last minstack
// if (this.stack[this.stack.length - 1] === this.minstack[this.minstack.length - 1]) {
// this.minstack.pop();
// }
// this.stack.pop();
// }
// top () {
// return this.stack[this.stack.length - 1];
// }
// getMin () {
// return this.minstack[this.minstack.length - 1];
// }
// }
var MinStack = function () {
this.stack = [];
this.minstack = [];
};
/**
* @param {number} val
* @return {void}
*/
MinStack.prototype.push = function (val) {
if (
this.minstack.length === 0 ||
val <= this.minstack[this.minstack.length - 1]
) {
this.minstack.push(val);
}
this.stack.push(val);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function () {
if (
this.minstack[this.minstack.length - 1] ===
this.stack[this.stack.length - 1]
) {
this.minstack.pop();
}
this.stack.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function () {
return this.stack[this.stack.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function () {
return this.minstack[this.minstack.length - 1];
};
// /**
// * Your MinStack object will be instantiated and called as such:
// * var obj = new MinStack()
// * obj.push(val)
// * obj.pop()
// * var param_3 = obj.top()
// * var param_4 = obj.getMin()
// */