LeetCode - Algorithms - 155. Min Stack

The solution of two stack is clear for me.

Java

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
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;

/** initialize your data structure here. */
public MinStack() {
stack = new Stack<Integer>();
minStack = new Stack<Integer>();
}

public void push(int x) {
stack.push(x);
if (minStack.isEmpty() || minStack.peek()>=x)
minStack.push(x);
}

public void pop() {
int x = stack.pop();
if (x==minStack.peek())
minStack.pop();
}

public int top() {
return stack.peek();
}

public int getMin() {
return minStack.peek();
}
}

/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/

Submission Detail

  • 18 / 18 test cases passed.
  • Runtime: 64 ms
  • Your runtime beats 96.51 % of java submissions.

JavaScript

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
/**
* initialize your data structure here.
*/
var MinStack = function(stk,minStk) {
this.stk = [];
this.minStk = [];
};

/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stk.push(x);
if (this.minStk.length==0 || this.minStk[this.minStk.length-1]>=x)
this.minStk.push(x);
};

/**
* @return {void}
*/
MinStack.prototype.pop = function() {
var x = this.stk.pop();
if (x==this.minStk[this.minStk.length-1])
this.minStk.pop();
};

/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stk[this.stk.length-1];
};

/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.minStk[this.minStk.length-1];
};

/**
* Your MinStack object will be instantiated and called as such:
* var obj = Object.create(MinStack).createNew()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/

Submission Detail

  • 18 / 18 test cases passed.
  • Runtime: 68 ms
  • Your runtime beats 100.00 % of javascript submissions.

ref