알고리즘/test

LIFO - example 2

이경찬 :) 2023. 3. 6. 10:56

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

문제:

정수 온도 배열이 일교차를 나타내는 경우, [i]라는 대답이 더 따뜻한 온도를 얻기 위해 하루 후에 기다려야 하는 일수가 되도록 배열 응답을 반환합니다. 이 작업이 가능한 미래 날짜가 없으면 [i] == 0으로 답하십시오

출력예시

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]

실행코드

def dailyTemperatures(temperatures):
  ans = [0] * len(temperatures)
  stack = []
  for cur_day, cur_temp in enumerate(temperatures):
    while stack and stack[-1][1] < cur_temp:
      prev_day, _ = stack.pop()
      ans[prev_day] = cur_day - prev_day
    stack.append((cur_day, cur_temp))
  return ans

풀이

stack을 이용한 LIFO의 풀이입니다.

1. return을 해줄 ans배열을 temperatures의 길이만큼 빈 배열을 선언 해 줍니다.

2. stack을 생성해줍니다.

3. enumerate를 이용하여 현재 index(cur_dau) 와 현재 온도 (cur_temp)를 입력받는 for문을 실행합니다.

4. while문을 사용하여 만약 스택이 채워져있거나 stack의 맨 위의 부분이 현재 입력받은 온도보다 낮다면 stack의 맨위 부분을 pop해줍니다. 이때 prev_day로 몇번쨰로 받아왔는지 저장해줍니다 ans에 append를 해줄 날짜는 현재에서 들어온 index를 빼준 날짜입니다.