-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path155 Min Stack.js
More file actions
97 lines (84 loc) · 1.54 KB
/
Copy path155 Min Stack.js
File metadata and controls
97 lines (84 loc) · 1.54 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* @constructor
*/
var MinStack = function() {
this.min = [];
this.stack = [];
};
/**
* @param {number} x
* @returns {void}
*/
MinStack.prototype.push = function(x) {
var min = this.getMin();
this.stack.push(x);
if (min === undefined || min >= x) {
this.min.push(x);
}
};
/**
* @returns {void}
*/
MinStack.prototype.pop = function() {
var val = this.stack.pop();
var min = this.getMin();
if (val === min) {
this.min.pop();
}
};
/**
* @returns {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length - 1];
};
/**
* @returns {number}
*/
MinStack.prototype.getMin = function() {
return this.min[this.min.length - 1];
};
// 112ms faster than ~80.85% and 44.2MB less than ~74.44%
var MinStack = function() {
this.min = Infinity;
this.stack = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
if (x < this.min) this.min = x;
this.stack.push(x);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
let newMin = Infinity;
this.stack.pop();
this.stack.forEach(e => {
if (e < newMin) newMin = e;
});
this.min = newMin;
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.min;
};
/**
* 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()
*/