λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 155 - Min Stack (Easy)

by HandHand 2021. 3. 2.

문제

LeetCode - 155번

풀이 κ³Όμ •

μŠ€νƒ 을 μ‚¬μš©ν•΄μ„œ 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;
};
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€