155. Min Stack #
Problem #
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.
Problem Summary #
This problem is about implementing a data structure. It requires implementing a stack class with push(), pop(), top(), and getMin().
Solution Approach #
Just implement it according to the problem requirements.
Code #
package leetcode
// MinStack define
type MinStack struct {
elements, min []int
l int
}
/** initialize your data structure here. */
// Constructor155 define
func Constructor155() MinStack {
return MinStack{make([]int, 0), make([]int, 0), 0}
}
// Push define
func (this *MinStack) Push(x int) {
this.elements = append(this.elements, x)
if this.l == 0 {
this.min = append(this.min, x)
} else {
min := this.GetMin()
if x < min {
this.min = append(this.min, x)
} else {
this.min = append(this.min, min)
}
}
this.l++
}
func (this *MinStack) Pop() {
this.l--
this.min = this.min[:this.l]
this.elements = this.elements[:this.l]
}
func (this *MinStack) Top() int {
return this.elements[this.l-1]
}
func (this *MinStack) GetMin() int {
return this.min[this.l-1]
}