Merge branch 'master' of git.hxr.so:yige/js-practice
This commit is contained in:
commit
f391e66174
@ -286,9 +286,15 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
## 栈
|
||||
|
||||
- [最大矩阵](src/stack/maximal-rectangle.js)
|
||||
|
||||
- LeetCode 85. 最大矩阵 <https://leetcode-cn.com/problems/maximal-rectangle/>
|
||||
- LintCode 510. 最大矩阵 <https://www.lintcode.com/problem/maximal-rectangle/description>
|
||||
|
||||
- [最小栈](src/stack/min-stack.js)
|
||||
|
||||
- LeetCode 155. 最小栈 <https://leetcode-cn.com/problems/min-stack/>
|
||||
- LintCode 12. 带最小值操作的栈 <https://www.lintcode.com/problem/min-stack/description>
|
||||
|
||||
## 数学
|
||||
|
||||
- [阶乘后的零](src/math/factorial-trailing-zeroes.js)
|
||||
|
47
src/stack/min-stack.js
Normal file
47
src/stack/min-stack.js
Normal file
@ -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()
|
||||
*/
|
13
test/stack/min-stack.test.js
Normal file
13
test/stack/min-stack.test.js
Normal file
@ -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)
|
||||
})
|
Loading…
Reference in New Issue
Block a user