-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminStack.js
83 lines (71 loc) · 1.68 KB
/
minStack.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
71
72
73
74
75
76
77
78
79
80
81
82
83
// Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
// push(x) -- Push element x onto stack.
// pop() -- Removes the element on top of the stack.
// top() -- Get the top element.
// getMin() -- Retrieve the minimum element in the stack.
// Example:
// MinStack minStack = new MinStack();
// minStack.push(-2);
// minStack.push(0);
// minStack.push(-3);
// minStack.getMin(); --> Returns -3.
// minStack.pop();
// minStack.top(); --> Returns 0.
// minStack.getMin(); --> Returns -2.
// SOLUTION ONE
var MinStack = function () {
this.stack = []
}
MinStack.prototype.push = function (x) {
this.stack.push(x)
}
MinStack.prototype.pop = function () {
this.stack.pop()
}
MinStack.prototype.top = function () {
let len = this.stack.length
if (len > 0) {
return this.stack[len - 1]
}
}
MinStack.prototype.getMin = function () {
let stack = this.stack
let tempMin = stack[0]
for (let i = 1; i < stack.length; i++) {
if (tempMin > stack[i]) {
tempMin = stack[i]
}
}
return tempMin
}
// A BETTER SOLUTION
// O(n) => O(1)
var MinStack = function () {
this.stack = []
this.min = []
}
MinStack.prototype.push = function (x) {
let preMin = this.getMin()
if (preMin !== undefined) {
preMin > x ? this.min.push(x) : this.min.push(preMin)
} else {
this.min.push(x)
}
this.stack.push(x)
}
MinStack.prototype.pop = function () {
this.stack.pop()
this.min.pop()
}
MinStack.prototype.top = function () {
let len = this.stack.length
if (len > 0) {
return this.stack[len - 1]
}
}
MinStack.prototype.getMin = function () {
let len = this.min.length
if (len > 0) {
return this.min[len - 1]
}
}