Skip to content

Commit 482f6c6

Browse files
add solution for 155 in js
1 parent b752282 commit 482f6c6

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

solution/155.Min Stack/Solution.js

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* initialize your data structure here.
3+
*/
4+
const MinStack = function() {
5+
this.arr = [];
6+
this.help = [];
7+
};
8+
9+
/**
10+
* @param {number} x
11+
* @return {void}
12+
*/
13+
MinStack.prototype.push = function(x) {
14+
this.arr.push(x);
15+
if(this.help.length === 0){
16+
this.help.push(0);
17+
}else{
18+
let min = this.getMin();
19+
if(x < min){
20+
this.help.push(this.arr.length-1);
21+
}
22+
}
23+
};
24+
25+
/**
26+
* @return {void}
27+
*/
28+
MinStack.prototype.pop = function() {
29+
if(this.arr.length === 0){
30+
throw new Error('???');
31+
}
32+
if(this.arr.length - 1 === this.help[this.help.length - 1]){
33+
this.help.pop();
34+
}
35+
this.arr.pop();
36+
};
37+
38+
/**
39+
* @return {number}
40+
*/
41+
MinStack.prototype.top = function() {
42+
return this.arr[this.arr.length-1];
43+
};
44+
45+
/**
46+
* @return {number}
47+
*/
48+
MinStack.prototype.getMin = function() {
49+
if(this.arr.length === 0){
50+
throw new Error("???");
51+
}
52+
return this.arr[this.help[this.help.length-1]];
53+
};
54+
55+
/**
56+
* Your MinStack object will be instantiated and called as such:
57+
* var obj = Object.create(MinStack).createNew()
58+
* obj.push(x)
59+
* obj.pop()
60+
* var param_3 = obj.top()
61+
* var param_4 = obj.getMin()
62+
*/

0 commit comments

Comments
 (0)