-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy path155 Min Stack.js
54 lines (44 loc) · 855 Bytes
/
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
// Leetcode #155
// Language: Javascript
// Problem: https://leetcode.com/problems/min-stack/
// Author: Chihung Yu
/**
* @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];
};