๊ฐœ๋ฐœ/๐Ÿค– ์•Œ๊ณ ๋ฆฌ์ฆ˜

[leetcode][Medium][Stack] 739. Daily Temperatures ํ’€์ด, ํ•ด์„ค (python)

ttoance 2023. 11. 12. 00:07

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

 

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

 

 

1์ฐจ ํ’€์ด 

class Solution(object):
    def dailyTemperatures(self, temperatures):
        """
        :type temperatures: List[int]
        :rtype: List[int]
        """
        
        stack = [0]
        res = [0] * len(temperatures)
        checked = 1 
        
        while checked < len(temperatures):
            while len(stack) > 0:
                if temperatures[checked] > temperatures[stack[-1]]:
                    res[stack[-1]] = checked - stack[-1]
                    stack.pop()
                else:
                    break
            
            stack.append(checked)
            checked += 1
        
        return res

 

ํ•ด์„ค

https://www.youtube.com/watch?v=cTBiBSnjO3c

while๋ฌธ์œผ๋กœ ํ–ˆ๋˜ ๋‚ด ํ’€์ด๋ฅผ ๋น„๊ต์  ๋‹จ์ˆœํ•˜๊ฒŒ ํ’€์—ˆ๋‹ค. 

  res = [0] * len(temperatures)
  stack = [] # pair [temp, index]

  for i,t in enumerate(temperatures):
        while stack and t > stack[-1][0]:
            stackT, stackInd = stack.pop()
            res[stackInd] = (i - stackInd)
        stack.append([t, i])     
  return res
๋ฐ˜์‘ํ˜•