์•Œ๊ณ ๋ฆฌ์ฆ˜๐Ÿฅš/๋ฌธ์ œํ’€์ด (Python)

[LeetCode] 739. daily_temperatures (Medium) 2023/5/9

๐Ÿช„ํ•˜๋ฃจ๐Ÿช„ 2023. 5. 9. 01:20
728x90
๋ฌธ์ œ ์ œ๋ชฉ ์ •๋‹ต๋ฅ  ๋‚œ์ด๋„
739. daily_temperatures 66.3% Medium
 

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) ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ์ด๊ณ , ์›์†Œ๋Š” 30 ์ด์ƒ 100 ์ดํ•˜์˜ ์ •์ˆ˜ ๊ฐ’์ด ์ฃผ์–ด์ง„๋‹ค

 

 

ํ’€์ด 1

์Šคํƒ์ด์šฉ (๋‹จ, ์Šคํƒ์— ๊ฐ’์„ ์ €์žฅํ•˜์ง€ ์•Š๊ณ  ์ธ๋ฑ์Šค๋ฅผ ์ €์žฅํ•œ๋‹ค)

Step1. ์ƒ์Šน๊ตฌ๊ฐ„ ํŒ๋‹จ(์ด์ „ ๊ฐ’๋ณด๋‹ค ๊ฐ’์ด ํฐ ์ง€์ ์„ ํ™•์ธ)

  • ์ƒ์Šน๊ตฌ๊ฐ„์ด ์•„๋‹ˆ๋ฉด ์Šคํƒ์— ํ•ด๋‹น ์˜จ๋„๊ฐ’๊ณผ ๋Œ€์‘๋˜๋Š” ์ธ๋ฑ์Šค ์ €์žฅ
  • ์ƒ์Šน๊ตฌ๊ฐ„์ด๋ฉด ์Šคํƒ์˜ ๊ฐ’๋“ค๊ณผ ๋น„๊ตํ•˜์—ฌ ํ˜„์žฌ ๊ฐ’์ด ๋” ํฐ ์ง€์ ๋“ค์— ๋Œ€ํ•ด ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ์— ๋‚ ์งœ ๊ณ„์‚ฐํ•˜์—ฌ ์—…๋ฐ์ดํŠธ ํ›„, ํ•ด๋‹น ์ง€์ ์„ ์Šคํƒ์—์„œ ์‚ญ์ œ

 

 

๊ตฌํ˜„ (1132ms)

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        idx_stack=[]
        result=[0 for i in range(len(temperatures))]
        for idx, value in enumerate(temperatures):
            while len(idx_stack)!=0 and value>temperatures[idx_stack[-1]]:
                last_idx=idx_stack.pop()
                result[last_idx]=(idx-last_idx)
            idx_stack.append(idx)
        return result
728x90