LeetCode Min Stack

twisted-fate發表於2019-06-03

覆盤:

可以不初始化大小 , 用append可以自動擴容

邊界條件判斷
LeetCode Min Stack

LeetCode Min Stack

這樣會減到負值
LeetCode Min Stack

LeetCode Min Stack

畫圖:

LeetCode Min Stack

LeetCode Min Stack

pesudo code :

Stack {
    dataArr []int
    dataHead int
}

push (v) {
    dataArr[dataHead]=v
    dataHead++
}

pop () {
    dataHead--
    return dataArr[dataHead]
}

top() {
    return dataArr[datahead-1]
}

getMin() {

}

MinStack {
    dataStack Stack
    minStack Stack
}

push (v) {
    dataS.push(v)
    if v>minS.top() {
        minS.push(v)
    }
}

pop () {
    v = dataS.pop()
    if v==minS.top() {
        minS.pop()
    }
    return v
}

top() {
    return dataS.top()
}

getMin() {
    return minS.top()
}

go implementation :

type MinStack struct {
    dataStack *Stack
    minStack *Stack
}

/** initialize your data structure here. */
func Constructor() MinStack {
    return MinStack{dataStack:&Stack{data:make([]int,9999),head:0},minStack:&Stack{data:make([]int,9999),head:0}}
}

func (this *MinStack) Push(x int)  {
    this.dataStack.Push(x)
    if this.minStack.isEmpty() || x<=this.minStack.Top() {
        this.minStack.Push(x)
    }
}

func (this *MinStack) Pop()  {
    v:=this.dataStack.Top()
    if  v==this.minStack.Top() {
        this.minStack.Pop()
    }
    this.dataStack.Pop()
}

func (this *MinStack) Top() int {
    return this.dataStack.Top()
}

func (this *MinStack) GetMin() int {
    return this.minStack.Top()
}

type Stack struct {
    data []int
    head int
}

func (this *Stack) Push(x int)  {

    this.data[this.head]=x
    this.head++
}

func (this *Stack) Pop()  {
    this.head--
}

func (this *Stack) isEmpty() bool {
    if this.head==0 {
        return true

    }
    return false
}

func (this *Stack) Top() int {
    return this.data[this.head-1]
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結