본문 바로가기

리트코드/midium

[리트코드] 739. Daily Temperatures - js

반응형

1. 문제

https://leetcode.com/problems/daily-temperatures/description/

 

Daily Temperatures - LeetCode

Can you solve this real interview question? Daily Temperatures - Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer

leetcode.com

2. 코드

/**
 * @param {number[]} temperatures
 * @return {number[]}
 */
var dailyTemperatures = function(temperatures) {
    let answer = [];

    for(let i=0;i<temperatures.length;i++){
        let wait = 0;
        for(let j=i;j<temperatures.length;j++){
            if(temperatures[i] < temperatures[j]){
                answer[i] = wait;
                wait = 0;
                break;
            }
            else wait += 1;
        }
        if(wait) answer[i] = 0;
    }

    return answer;
};

나는 무지 간단한 방법(직관적인..)으로 풀었지만, 탑-다운 / 바텀-업 풀이를 사용한 좋은 코드들이 있었다.

https://leetcode.com/problems/daily-temperatures/solutions/2912495/javascript-stack-top-down-bottom-up/

내 풀이(위의 코드)의 결과는 다음과 같았다.

스택을 사용한 탑-다운 방식의 결과는 다음과 같았다. 훨씬 더 좋은 풀이 방법이다.

var dailyTemperatures = function(temperatures) {
    let stack = [];
    let res = new Array(temperatures.length).fill(0);
    
    for (let i = 0; i < n; i++) {
        while (stack.length && temperatures[i] > temperatures[stack[stack.length-1]]) {
            let idx = stack.pop();
            res[idx] = i - idx;;
        }
        stack.push(i);
    }

    return res;
};
반응형