From 7055121867ef5cf05e0332ca20ea8b46ea549112 Mon Sep 17 00:00:00 2001 From: yige Date: Tue, 12 May 2020 22:30:19 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E6=9C=80=E5=B0=8F=E6=A0=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++++ src/stack/min-stack.js | 47 ++++++++++++++++++++++++++++++++++++ test/stack/min-stack.test.js | 13 ++++++++++ 3 files changed, 66 insertions(+) create mode 100644 src/stack/min-stack.js create mode 100644 test/stack/min-stack.test.js diff --git a/README.md b/README.md index afed3c5..72c5972 100644 --- a/README.md +++ b/README.md @@ -286,9 +286,15 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 ## 栈 - [最大矩阵](src/stack/maximal-rectangle.js) + - LeetCode 85. 最大矩阵 - LintCode 510. 最大矩阵 +- [最小栈](src/stack/min-stack.js) + + - LeetCode 155. 最小栈 + - LintCode 12. 带最小值操作的栈 + ## 数学 - [阶乘后的零](src/math/factorial-trailing-zeroes.js) diff --git a/src/stack/min-stack.js b/src/stack/min-stack.js new file mode 100644 index 0000000..7de17fd --- /dev/null +++ b/src/stack/min-stack.js @@ -0,0 +1,47 @@ +/** + * initialize your data structure here. + */ +export const MinStack = function () { + this.stack = [] + this.minStack = [Infinity] +} + +/** + * @param {number} x + * @return {void} + */ +MinStack.prototype.push = function (x) { + this.stack.push(x) + this.minStack.push(Math.min(this.minStack[this.minStack.length - 1], x)) +} + +/** + * @return {void} + */ +MinStack.prototype.pop = function () { + this.stack.pop() + this.minStack.pop() +} + +/** + * @return {number} + */ +MinStack.prototype.top = function () { + return this.stack[this.stack.length - 1] +} + +/** + * @return {number} + */ +MinStack.prototype.getMin = function () { + return this.minStack[this.minStack.length - 1] +} + +/** + * Your MinStack object will be instantiated and called as such: + * var obj = new MinStack() + * obj.push(x) + * obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.getMin() + */ diff --git a/test/stack/min-stack.test.js b/test/stack/min-stack.test.js new file mode 100644 index 0000000..798a97b --- /dev/null +++ b/test/stack/min-stack.test.js @@ -0,0 +1,13 @@ +import { MinStack } from '../../src/stack/min-stack' + +test('最小栈', () => { + var obj = new MinStack() + obj.push(1) + obj.push(3) + obj.push(2) + obj.pop() + var top = obj.top() + var min = obj.getMin() + expect(top).toBe(3) + expect(min).toBe(1) +})