工作生活

Min Stack

2019-07-02  本文已影响0人  carlclone

复盘:

可以不初始化大小 , 用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]
}
上一篇 下一篇

猜你喜欢

热点阅读