• 最小栈


    • 使用切片slice实现
    type MinStack struct {
        stack []int
        minIndex int
        length int
    }
    
    
    /** initialize your data structure here. */
    func Constructor() MinStack {
        return MinStack{}
    }
    
    
    func (this *MinStack) Push(val int)  {
        this.stack = append(this.stack, val)
        this.minIndex = this.calculateMinIndex()
        this.length++
    }
    
    
    func (this *MinStack) Pop()  {
        this.stack = this.stack[:len(this.stack)-1]
        this.minIndex = this.calculateMinIndex()
        this.length--
    }
    
    
    func (this *MinStack) Top() int {
        return this.stack[this.length-1]
    }
    
    
    func (this *MinStack) GetMin() int {
        return this.stack[this.minIndex]
    }
    
    func (this *MinStack)calculateMinIndex()int{
        var min_index = 0
        for i:=1;i<len(this.stack);i++{
            if this.stack[i]<this.stack[min_index]{
                min_index = i
            }
        }
        return min_index
    }
    

    • 使用list.List实现(双链表)
    type MinStack struct {
    	min int
    	stack list.List
    }
    
    
    /** initialize your data structure here. */
    func Constructor() MinStack {
    	return MinStack{min:math.MaxInt64}
    }
    
    
    func (this *MinStack) Push(val int)  {
    	if val<this.min{
    		this.min = val
    	}
    	this.stack.PushBack(val)
    }
    
    
    func (this *MinStack) Pop()  { 
        if this.min==this.stack.Back().Value.(int){
            this.stack.Remove(this.stack.Back())
            this.min = math.MaxInt64
            for e:=this.stack.Front();e!=nil;e=e.Next(){
                val := e.Value.(int)
                if val<this.min{
                    this.min = val
                }
            }
        }else{
            this.stack.Remove(this.stack.Back())
        }
        
    }
    
    
    func (this *MinStack) Top() int {
    	return this.stack.Back().Value.(int)
    }
    
    
    func (this *MinStack) GetMin() int {
    	return this.min
    }
    
    

  • 相关阅读:
    编程的核心思维
    对编程语言的一点总结
    End Poem
    linux下的errno对照表
    C++中的三个特殊宏:__FILE__,__FUNCTION__和__LINE__
    算法——从斐波那契数列谈起(一)
    [题解][HNOI2002][Luogu P2234] 营业额统计
    用STL水平衡树的题
    浅谈C++的智能指针
    cnblog代码高亮优化(tomorrow主题)
  • 原文地址:https://www.cnblogs.com/pangqianjin/p/14636030.html
Copyright © 2020-2023  润新知