๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 739 - Daily Temperatures (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 739๋ฒˆ

ํ’€์ด ๊ณผ์ •

๊ฐ ๋‚ ์˜ ์˜จ๋„ ์ •๋ณด๊ฐ€ ๋ฐฐ์—ด๋กœ ์ฃผ์–ด์งˆ ๋•Œ ๊ฐ ๋‚ ์˜ ์˜จ๋„๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ธฐ์˜จ์ด ์ƒ์Šนํ•˜๋Š” ์ตœ์ดˆ์˜ ๋‚ ์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋ธŒ๋ฃจํŠธ ํฌ์Šค ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ๋”ฐ์งˆ ๊ฒฝ์šฐ O(N^2) ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ์‹œ๋„ํ•ด๋ณผ ์ˆ˜ ์žˆ๊ฒ ์ง€๋งŒ
์ž…๋ ฅ ๊ฐ’์˜ ํฌ๊ธฐ ๋•Œ๋ฌธ์— ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค. ๋Œ€์‹ ์— ์Šคํƒ ์„ ์‚ฌ์šฉํ•˜๋ฉด O(N) ์— ์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์Šคํƒ ์— ๊ฐ ๋‚ ์งœ์˜ ์˜จ๋„๋ฅผ ์ธ๋ฑ์Šค์™€ ํ•จ๊ป˜ ์ €์žฅํ•˜๋ฉฐ ๋งŒ์•ฝ ์ƒˆ๋กœ ๋“ค์–ด์˜ค๋Š” ๋‚ ์งœ์˜ ์˜จ๋„๊ฐ€ top ๋ณด๋‹ค ๋†’์„ ๊ฒฝ์šฐ์—๋Š”
ํ•ด๋‹น ๋‚ ์งœ๋ณด๋‹ค ์˜จ๋„๊ฐ€ ๋†’์€ ๋‚ ์ด ๋‚จ์„๋•Œ๊นŒ์ง€ pop ํ•ด์ฃผ๋ฉฐ ๋‚ ์งœ ๊ฐ„๊ฒฉ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.

๋งŒ์•ฝ ์ตœ์ข…์ ์œผ๋กœ ์Šคํƒ ์ด ๋น„์–ด์žˆ์ง€ ์•Š๋‹ค๋ฉด ๋‚จ์•„์žˆ๋Š” ์˜จ๋„๋Š” ๋ชจ๋‘ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ๋˜์–ด ์žˆ๋Š” ๊ฒƒ์ด๋ฏ€๋กœ 0 ์œผ๋กœ ํ•ด์ฃผ๋ฉด ๋˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} T
 * @return {number[]}
 */
var dailyTemperatures = function (T) {
  const stack = [];
  const answer = [];

  for (let i = 0; i < T.length; i++) {
    if (!stack.length || top(stack) >= T[i]) {
      stack.push([T[i], i]);
    } else {
      while (stack.length > 0 && top(stack)[0] < T[i]) {
        answer[top(stack)[1]] = i - top(stack)[1];
        stack.pop();
      }
      stack.push([T[i], i]);
    }
  }

  if (stack.length) {
    stack.forEach((s) => (answer[s[1]] = 0));
  }

  return answer;
};

function top(stack) {
  return stack[stack.length - 1];
}
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 394 - Decode String (Medium)  (0) 2021.03.03
LeetCode 78 - Subsets (Medium)  (0) 2021.03.03
LeetCode 114 - Flatten Binary Tree to Linked List (Medium)  (0) 2021.03.03
LeetCode 287 - Find the Duplicate Number (Medium)  (0) 2021.03.03
LeetCode 347 - Top K Frequent Elements (Medium)  (0) 2021.03.03

๐Ÿ’ฌ ๋Œ“๊ธ€