題目描述
實現一個棧, 支持以下操作:
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();
}
}