Lint Code:一天一道算法题_1(带最小值操作的栈)

题目描述

实现一个栈, 支持以下操作:

push(val) 将 val 压入栈
pop() 将栈顶元素弹出, 并返回这个弹出的元素
min() 返回栈中元素的最小值

要求 O(1) 开销.
保证栈中没有数字时不会调用 min()

题目链接: 带最小值操作的栈

Python题解

class Stack:
    def __init__(self):
        self._lst = []
    def push(self,val):
        self._lst.append(val)
        print("stack: "+str(self._lst))
    def pop(self):
        p = self._lst.pop()
        print("stack: "+str(self._lst))
        return p
    def min(self):
        if self._lst:
            minnum = min(self._lst)
            print("min: "+str(minnum))
            return minnum



if __name__ == '__main__':
    stack = Stack()
    stack.push(1)
    stack.min()
    stack.push(2)
    stack.min()
    stack.push(3)
    stack.min()

Javascript题解

//基于原型的面向对象
<script>
function Stack() {}
Stack.prototype.lst = [];
Stack.prototype.push = function (num) {
	this.lst.push(num);
	console.log(this.lst);
};
Stack.prototype.pop = function () {
	let p =this.lst.pop();
	console.log(this.lst);
	return p;
};
Stack.prototype.min = function () {
	if(this.lst){
		let min = this.lst.sort(function(a, b){return a - b})[0];
		console.log("min: "+min);
		return min; 
	}
	else{
		return null;
	}
};
var stack = new Stack();
stack.push(1);
stack.min();
stack.push(2);
stack.min();
stack.push(3);
stack.min();
</script>

Java题解

package com.company;

import java.util.ArrayList;

public class Stack {
    private ArrayList<Integer> lst;

    public Stack(){
        this.lst = new ArrayList<>();
    }
    public void push(int number) {
        this.lst.add(number);
    }

    public int pop() {
        return this.lst.remove(this.lst.size() - 1);
    }

    public int min() {
        if(this.lst.size() > 0){
            int minnum = this.lst.get(0);
            for(int i = 0; i <this.lst.size();i ++){
                if(minnum > this.lst.get(i)){
                    minnum = this.lst.get(i);
                }
            }
            return minnum;
        }
        return 0;
    }

    public static void main(String[] args) {
        Stack stack = new Stack();
        stack.push(1);
        stack.pop();
        stack.push(2);
        stack.push(3);
        stack.min();
        stack.push(1);
        stack.min();
    }
}

发布了29 篇原创文章 · 获赞 129 · 访问量 8697

猜你喜欢

转载自blog.csdn.net/weixin_44072077/article/details/105177190