-
Notifications
You must be signed in to change notification settings - Fork 0
/
155-min-stack.js
70 lines (64 loc) · 1.38 KB
/
155-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
var MinStack = function () {
this.current = -1;
this.min = -1;
this.stack = [];
this.previousMinIndex = -1;
this.previousMin = [];
};
/**
* @param {number} val
* @return {void}
*/
MinStack.prototype.push = function (val) {
this.current++;
if (this.min === -1) {
this.min = this.current;
} else if (val < this.stack[this.min]) {
this.previousMinIndex++;
if (this.previousMin.length - 1 < this.previousMinIndex) {
this.previousMin.push(this.min);
} else {
this.previousMin[this.previousMinIndex] = this.min;
}
this.min = this.current;
}
if (this.stack.length - 1 < this.current) {
this.stack.push(val);
} else {
this.stack[this.current] = val;
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function () {
if (this.current === this.min) {
if (this.previousMinIndex === -1) {
this.min = -1;
} else {
this.min = this.previousMin[this.previousMinIndex];
this.previousMinIndex--;
}
}
this.current--;
};
/**
* @return {number}
*/
MinStack.prototype.top = function () {
return this.stack[this.current];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function () {
return this.stack[this.min];
};
/**
* 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()
*/