1.使用栈获取最小值

代码块

例如:

#coding=utf-8


class Stack(object):
    def __init__(self):
        self.__items = []

    def is_empty(self):
        return self.__items == []

    def peek(self):
        return self.__items[-1]

    def pop(self):
        return self.__items.pop()

    def size(self):
        return len(self.__items)

    def push(self, item):
        self.__items.append(item)


class MinStack(object):

    def __init__(self):
        self.data_stack = Stack()
        self.min_stack = Stack()

    def pop(self):
        if not self.data_stack.is_empty():
            result = self.data_stack.pop()
            if result == self.min_stack.peek():
                self.min_stack.pop()
            return result
        else:
            return -1

    def peek(self):
        return self.data_stack.peek()

    def push(self, item):
        self.data_stack.push(item)
        if self.min_stack.is_empty() or item <= self.min_stack.peek():
            self.min_stack.push(item)


    def get_min(self):
        if not self.min_stack.is_empty():
            return self.min_stack.peek()
        else:
            return -1


def test1():
    min_stack = MinStack()
    min_stack.push(3)
    min_stack.push(4)
    min_stack.push(5)
    min_stack.push(1)
    min_stack.push(3)
    min_stack.push(1)
    min_stack.push(2)
    print min_stack.get_min()
    min_stack.pop()
    min_stack.pop()
    min_stack.pop()
    min_stack.pop()
    print min_stack.get_min()


def main():
    test1()


if __name__ == '__main__':
    main()
//使用数组模拟两个栈 一个放所有数据一个存放最小数据
var data_stack = [];
var min_stack = [];

//栈的push
function spush(val){
    data_stack.push(val);
    if(min_stack.length == 0){
        min_stack.push(val)
    }
    else if(data_stack[data_stack.length-1] <= min_stack[min_stack.length -1]){
      min_stack.push(val)
    }
}
//栈的pop
function spop(){
    var res = data_stack.pop()
    if(res == min_stack[min_stack.length-1]){
        min_stack.pop()
    }
}
//获取最小值
function getMin(){
    if(min_stack.length !=0){
        return min_stack[min_stack.length-1]
    }
}
function test(){
    spush(3)
    spush(4)
    spush(2)
    spush(1)
    spush(2)
    spop()
    spop()
}
test();
console.log(getMin())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值