waveofmymind
기록하는 습관
waveofmymind
전체 방문자
오늘
어제
  • 분류 전체보기 (124)
    • 📝 정리 (5)
    • 🌊TIL (9)
    • 💻CS (1)
      • 자료구조 (1)
    • 📙Language (9)
      • ☕Java (6)
      • 🤖Kotlin (3)
    • 🍃Spring (28)
    • 👨🏻‍💻알고리즘 (67)
      • 프로그래머스 (59)
      • 백준 (3)
    • 👷DevOps (4)
      • 🐳Docker (2)
      • 🤵Jenkins (1)

블로그 메뉴

  • 홈
  • Spring
  • Java
  • 알고리즘

공지사항

인기 글

태그

  • spring boot
  • 통합테스트
  • JDBC
  • CORS
  • mybatis
  • SpringAOP
  • 스프링 부트
  • 트랜잭션 전파
  • 완전탐색
  • sql
  • til
  • AOP
  • kotlin
  • 스프링 시큐리티
  • Spring Security
  • 스프링
  • BFS
  • 코틀린
  • 스택
  • 챗GPT
  • 힙
  • Connection
  • spring
  • kotest
  • chat GPT
  • 다이나믹 프로그래밍
  • Open AI
  • LeetCode
  • 트랜잭션
  • resultset

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
waveofmymind

기록하는 습관

[LeetCode] Medium. Daily Temperatures
👨🏻‍💻알고리즘

[LeetCode] Medium. Daily Temperatures

2023. 2. 16. 14:44

문제 링크: https://leetcode.com/problems/daily-temperatures/

 

Daily Temperatures - LeetCode

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 temperature. If there is no future day for w

leetcode.com

접근

  • 해당 문제의 시간복잡도에 들어가는 배열의 길이가 10^5이므로, 시간복잡도 O(n) 밑으로 계산해야 한다.
  • 각 날의 온도를 타깃으로 하여 언제 따뜻한 날이 오는지 for문을 돌리게 되면 시간 초과가 발생한다.

코드

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        answer = [0] * len(temperatures)
        stack = []
        for day,t in enumerate(temperatures):
            while stack and stack[-1][1] < t:
                prev_day,prev_t = stack.pop()
                answer[prev_day] = day - prev_day
            stack.append((day,t))
        return answer

 

풀이

  • 스택을 이용하여 해결했다.
  • 유효한 괄호식인지 해결하는 문제처럼 해결하면 용이하다
    • 여는 괄호이면 푸시
    • 닫는 괄호이면, 가장 최근에 넣은 값이랑 짝이 맞으면 팝, 다를 경우 False
    • 모든 체크가 끝났을 때, 스택이 비어있으면 True, 스택에 값이 있으면 False
  • 더 들어가야 할 만한 점은, 괄호는 짝이 있으나, 이 문제는 현재 t보다 낮은 모든 온도에 대해 pop이 이루어져야 한다는 점이다.
  • stack에 인덱스, 값을 튜플로 넣어두고, 값을 뺄 때에는 stack [-1][1]과 t를 비교한다.
  • stack에 넣은 값이 t보다 작은 모든 값을 다 팝 해주고, 팝할때마다 튜플의 0번째 값인 인덱스와, 현재 t에 대한 인덱스 day를 뺀 값을 넣어준다.

'👨🏻‍💻알고리즘' 카테고리의 다른 글

[LeetCode] 70. Climbing Stairs  (0) 2023.02.28
[LeetCode] 841. Keys and Rooms  (0) 2023.02.24
[LeetCode] 1091. Shortest Path in Binary Matrix  (0) 2023.02.24
[LeetCode] 200. Number of Islands  (0) 2023.02.24
    '👨🏻‍💻알고리즘' 카테고리의 다른 글
    • [LeetCode] 70. Climbing Stairs
    • [LeetCode] 841. Keys and Rooms
    • [LeetCode] 1091. Shortest Path in Binary Matrix
    • [LeetCode] 200. Number of Islands
    waveofmymind
    waveofmymind

    티스토리툴바