[LeetCode#739] Daily Temperatures

2024. 7. 31. 18:05·Algorithm/문제풀이

❒ Description


제목 Daily Temperature
링크 https://leetcode.com/problems/daily-temperatures/description/
자료구조 스택
시간 복잡도 O(n)

 

이번 문제의 핵심은 인덱스이다. 

그리고 두 가지 풀이가 있는데 첫 번째는 Stack + Index 이고, 두 번째는 Index만을 사용하는 문제풀이다.

비교 이미지

 둘 해결책 모두 O(n)의 시간 복잡도를 가진다. 하지만 두번 째 솔루션이 6ms로 4배정도 빨랐다.

 

 

 

 

 

 

❒ Solution


1. Stack

아래 코드는 최초에 작성한 코드로 runtime 26ms를 기록한 코드이다.

 

public int[] dailyTemperatures(int[] temperatures) {
	int[] result = new int[temperatures];
	Queue<Integer> statck = new ArrayDeque<>();
   
	for (int i = 0; i < temperatures.length(); i++) {
		while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
			int last = stack.pop();
			result[last] = i - last;
		}
		stack.push(i);
	}
	return result;
}

 

 

2. Only Index

아래 코드는 leet-code solution에서 가장 빠른 runtime 6ms를 기록한 코드이다.

public int[] dailyTemperaturesV2(int[] temperatures) {
    int n = temperatures.length;
    int[] result = new int[n];
    int hottest = 0;
    for (int i = n-1; i >= 0; i--) {
        int cur = temperatures[i];
        if (cur >= hottest) {
            hottest = cur;
            continue;
        }

        int count = 1;
        while (cur >= temperatures[i + count]) {
            count += result[i + count];
        }
        result[i] = count;
    }
    return result;
}
코드 분석
  • for문을 역순으로 순회하고 있다.
  • 이전 결과 값 result[x]를 재사용한다.

Input이 `[9, 7, 5, 2, 10]`인 경우를 살펴봤다.

i hottest cur while문 순회 result
4 10 10 0 [ 0, 0, 0, 0, 0 ]
3 10 2 0 [ 0, 0, 0, 1, 0 ]
2 10 5 1 [ 0, 0, 2, 1, 0 ]
1 10 7 1 [ 0, 3, 2, 1, 0 ]
0 10 9 1 [ 4, 3, 2, 1, 0 ]

 

결과적으로 `temperatures[i]`는 `temperatures[i+1]`이 hottest 까지 몇 칸을 갔는지 확인하고 그

값에 1 만 더 한 것이다. 만약 바로 다음 값이 변곡점이라면 while 문을 순회하지 않고, count 값을 `result[i]`에

저장한다. 

 

 

 

 

 

❒ 왜 4배의 차이가 생길까?


1. Stack Operation

solution2는 stack 연산이 없다. 물론 push와 pop 연산이 O(1)의 시간 복잡도를 갖지만, 

여러번의 연산 과정이 있기 때문에 runtime에 차이가 발생한다.

 

2. Optimized while loop & Caching

solution2의 경우에는 solution1에 비해 while 조건문이 단순하다. 그리고 데이터를 재사용하는 빈도가 높아

Cache-Hit rate가 높다. 이 점이 실제 runtime 성능을 크게 향상시킨 것 같다.

 

  

 

 

 

 

 


'Algorithm > 문제풀이' 카테고리의 다른 글

[LeetCode#641] Design Circular Deque  (0) 2024.08.05
[LeetCode#622] Design Circular Queue  (0) 2024.08.04
[LeetCode#92] Reverse Linked List II  (0) 2024.07.28
[LeetCode#24] Swap Nodes In Pairs  (0) 2024.07.28
[LeetCode#206] Reverse Linked List  (0) 2024.07.28
'Algorithm/문제풀이' 카테고리의 다른 글
  • [LeetCode#641] Design Circular Deque
  • [LeetCode#622] Design Circular Queue
  • [LeetCode#92] Reverse Linked List II
  • [LeetCode#24] Swap Nodes In Pairs
gilbert9172
gilbert9172
gilbert9172 님의 블로그 입니다.
  • gilbert9172
    バックエンド
    gilbert9172
  • 전체
    오늘
    어제
    • All Categories (166)
      • 우테코 7기 (21)
        • 1주차 (8)
        • 2주차 (5)
        • 3주차 (6)
      • Langauge (4)
        • Java (3)
        • Kotlin (1)
      • Back-End (13)
        • SpringBoot (1)
        • Trouble Shooting (0)
        • Setup & Configuration (1)
        • SQL (3)
        • Redis (8)
      • Architecture (6)
        • Multi Module (1)
        • DDD (5)
      • CS (30)
        • Data Structure (6)
        • Operating System (0)
        • Network (12)
        • Database (10)
        • Design Pattern (2)
      • Algorithm (78)
        • 내용 정리 (18)
        • 문제풀이 (60)
      • DevOps (6)
        • AWS (5)
        • Git (1)
      • Front-End (1)
        • Trouble Shooting (1)
      • Project (6)
        • 페이스콕 (6)
      • Book (0)
        • 마스터링 블록체인 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Two-Pointer
    오블완
    부분단조성
    binarysearch
    greedy
    Back-Tracking
    sliding-window
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
gilbert9172
[LeetCode#739] Daily Temperatures
상단으로

티스토리툴바