T4——剑指 Offer 30. 包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
题目解析:
普通栈的 push() 和 pop() 函数的复杂度为 O(1),而获取栈最小值 min() 函数需要遍历整个栈,复杂度为 O(N)。
重点:将 min() 函数复杂度降为 O(1) ,可通过建立辅助栈实现;
栈 A:用于存储所有元素,保证入栈 push() 函数、出栈 pop() 函数、获取栈顶 top() 函数的正常逻辑。
栈 B:存储第一个入栈A的元素,之后所有入栈A的元素只要比栈B的栈顶元素小就入栈B。
push(x) 函数: 将x压入栈A;当栈B为空或者x小于等于栈B的栈顶元素,则压入栈B。(因为可能会有多个最小的数,当你将一个最小的数删除后,应该还剩下其他最小的数)
pop() 函数:将栈A栈顶元素出栈,并标记为y,若y等于栈B的栈顶元素,则将栈B的栈顶元素出栈。
top()函数:将栈A栈顶元素出栈
min()函数:将栈B栈顶元素出栈
代码:
class MinStack { A: number[] = []; B: number[] = []; constructor() {} push(x: number): void { if (this.B.length == 0 || x <= this.min()) { this.A.push(x); this.B.push(x); } else { this.A.push(x); } } pop(): void { const y = this.A.pop(); if (y == this.min()) { this.B.pop(); } } top(): number { return this.A[this.A.length - 1]; } min(): number { return this.B[this.B.length - 1]; } } var obj1 = new MinStack(); obj1.push(3); obj1.push(2); obj1.push(4); console.log(obj1.A); console.log(obj1.B); obj1.pop(); console.log(obj1.A); console.log(obj1.B); var param_3 = obj1.top(); var param_4 = obj1.min();
var list = function () { this.allList = []; this.minList = []; }; list.prototype.push = function (data) { this.allList.push(data); if (this.allList.length == 1) { this.minList.push(data); } if ( this.allList.length > 1 && data <= this.minList[this.minList.length - 1] ) { this.minList.push(data); } }; list.prototype.pop = function () { let y = this.allList.pop(); if (y == this.minList[this.minList.length - 1]) { this.minList.pop(); } }; list.prototype.min = function () { return this.minList[this.minList.length - 1]; }; list.prototype.top = function(){ return this.allList[this.allList.length - 1] } var newList = new list(); newList.push(-2); newList.push(0); newList.push(-3); console.log("newList.min()", newList.min()); newList.pop(); newList.top(); console.log("newList.min()", newList.min());
题目源自:
https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/