1. 程式人生 > >最小棧 go實現

最小棧 go實現

設計一個支援 push,pop,top 操作,並能在常數時間內檢索到最小元素的棧。

push(x) -- 將元素 x 推入棧中。
pop() -- 刪除棧頂的元素。
top() -- 獲取棧頂元素。
getMin() -- 檢索棧中的最小元素。
示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.
/**
 * Your MinStack object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * obj.Pop();
 * param_3 := obj.Top();
 * param_4 := obj.GetMin();
 */

type MinStack struct {
	elems []int
	mins  []int
}

/** initialize your data structure here. */
func Constructor() MinStack {
	return MinStack{make([]int, 0), make([]int, 0)}
}

func (this *MinStack) Push(x int) {
	this.elems = append(this.elems, x)

	if len(this.mins) == 0 || this.GetMin() >= x {
		this.mins = append(this.mins, x)
	}
}

func (this *MinStack) Pop() {
	elem := this.Top()
	this.elems = this.elems[:len(this.elems)-1]

	if elem <= this.GetMin() {
		this.mins = this.mins[:len(this.mins)-1]
	}
}

func (this *MinStack) Top() int {
	if len(this.elems) == 0 {
		panic("empty stack")
	}

	elem := this.elems[len(this.elems)-1]
	return elem
}

func (this *MinStack) GetMin() int {
	if len(this.mins) == 0 {
		panic("empty stack")
	}

	elem := this.mins[len(this.mins)-1]
	return elem
}