λ¬Έμ
νμ΄ κ³Όμ
μ€ν
μ μ¬μ©ν΄μ min stack
μ ꡬννλ λ¬Έμ μ
λλ€.
λ¨μνκ² κ΅¬ννλ©΄ μ΅μκ°μ μ°Ύμ λλ§λ€ Math.min
μ μ¬μ©ν μλ μμ§λ§
λ¬Έμ 쑰건과 κ°μ΄ μμ μκ°μ μ΅μκ°μ μ°ΎκΈ° μν΄μλ λ€λ₯Έ λ°©λ²μ΄ νμν©λλ€.
μ΄λ₯Ό μν΄ λ κ°μ μ€νμ μ¬μ©νμ¬ κ°μ μ μ₯νλλ‘ ν©λλ€.
νλλ λ€μ΄μ¨ μμλλ‘ μμ μ¬λ¦¬λ μ€νμ΄κ³ λ€λ₯Έ νλλ μ΄μ λμνμ¬ νμ¬κΉμ§μ μ΅μκ°μ μ μ₯νλ μ€νμΌλ‘ μ¬μ©ν©λλ€.
μλ₯Ό λ€μ΄ 1, 2, 0, 3
μ΄ μμλλ‘ μ
λ ₯λλ€κ³ νλ€λ©΄ λ κ°μ μ€νμ λ€μκ³Ό κ°μ μνλ₯Ό κ°μ§κ² λ©λλ€.
| 3 | | 0 |
| 0 | | 0 |
| 2 | | 1 |
| 1 | | 1 |
A μ€ν B μ€ν
λ°λΌμ minValue
λ₯Ό ν΅ν΄ νμ¬κΉμ§μ μ΅μκ°μ κ°±μ νλ©΄μ B μ€νμ push, pop
μ ꡬνν©λλ€.
μ½λ
/**
* initialize your data structure here.
*/
var MinStack = function () {
this.stack = [];
this.minStack = [];
this.minValue = Infinity;
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function (x) {
this.stack.push(x);
this.minValue = Math.min(this.minValue, x);
this.minStack.push(this.minValue);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function () {
this.stack.pop();
this.minStack.pop();
if (this.minStack.length > 0) {
this.minValue = this.minStack[this.minStack.length - 1];
} else {
this.minValue = Infinity;
}
};
/**
* @return {number}
*/
MinStack.prototype.top = function () {
return this.stack[this.stack.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function () {
return this.minValue;
};
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 21 - Merge Two Sorted Lists (Easy) (0) | 2021.03.02 |
---|---|
LeetCode 240 - Search a 2D Matrix II (Medium) (0) | 2021.03.02 |
LeetCode 39 - Combination Sum (Medium) (0) | 2021.03.02 |
LeetCode 20 - Valid Parentheses (Easy) (0) | 2021.03.02 |
LeetCode 787 - Cheapest Flights Within K Stops (Medium) (0) | 2021.03.02 |
π¬ λκΈ