|
| 1 | +# https://leetcode.com/problems/meeting-rooms-ii/ |
| 2 | + |
| 3 | +from typing import List |
| 4 | + |
| 5 | +class Solution: |
| 6 | + def minMeetingRooms_heap(self, intervals: List[List[int]]) -> int: |
| 7 | + """ |
| 8 | + [Complexity] |
| 9 | + - TC: O(nlogn) (sort & heappop/push) |
| 10 | + - SC: O(n) (min heap) |
| 11 | +
|
| 12 | + [Approach] |
| 13 | + ๊ธฐ๋ณธ์ ์ผ๋ก ํ์ ์์ ์๊ฐ์ด ๋น ๋ฅธ ์์๋ก ์ดํด๋ณด์์ผ ํ๋ค. |
| 14 | + ์์ ์๊ฐ ์ด์ ์ ์ด๋ค ํ์์ค์ด ๋น๋ค๋ฉด ํด๋น ํ์์ค์ ์ด์ด์ ์ฌ์ฉํ ์ ์๊ณ |
| 15 | + ์์ ์๊ฐ ์ดํ๊น์ง ๊ธฐ์กด ํ์๊ฐ ๋ง์น์ง ์๋๋ค๋ฉด ํด๋น ํ์์ค์ ์ฌ์ฉํ ์ ์๋ค. |
| 16 | + ์ด๋ฅผ ๋งค๋ฒ ๋น ๋ฅด๊ฒ ํ๋จํ๊ธฐ ์ํด์๋ ๊ทธ๋ฆฌ๋ํ๊ฒ |
| 17 | + "์ด์ ๊น์ง ํ์์ค์ ์ฌ์ฉํ๋ ํ์ ์ค ๊ฐ์ฅ ๋นจ๋ฆฌ ๋ง์น๋ ํ์์ ์ข
๋ฃ ์๊ฐ"๊ณผ "ํ์ฌ ๋ณด๊ณ ์๋ ํ์ ์์ ์๊ฐ" |
| 18 | + ์ ๋น๊ตํ๋ฉด ๋๋ค. |
| 19 | + ํญ์ ํ์์ ์ข
๋ฃ ์๊ฐ ์ค ๊ฐ์ฅ ์์ ๊ฐ์ ๊ณ ๋ฅด๋ฉด ๋๋ฏ๋ก, min heap์ ์ด์ฉํ์ฌ ์ต์๊ฐ์ O(1)์ ์กฐํํ ์ ์๋๋ก ํ ์ ์๋ค. |
| 20 | + """ |
| 21 | + import heapq |
| 22 | + |
| 23 | + # ํ์ ์์ ์๊ฐ ์์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌ |
| 24 | + intervals.sort() |
| 25 | + |
| 26 | + # min heap |
| 27 | + rooms = [] |
| 28 | + |
| 29 | + for s, e in intervals: |
| 30 | + # "์ด์ ๊น์ง ํ์์ค์ ์ฌ์ฉํ๋ ํ์ ์ค ๊ฐ์ฅ ๋นจ๋ฆฌ ๋ง์น๋ ํ์์ ์ข
๋ฃ ์๊ฐ"๊ณผ "ํ์ฌ ๋ณด๊ณ ์๋ ํ์ ์์ ์๊ฐ"์ด ๊ฒน์น์ง ์๋ ๊ฒฝ์ฐ, |
| 31 | + # rooms์ ์กด์ฌํ๋ ํ์์ค ์ค e๊ฐ ๊ฐ์ฅ ์ด๋ฅธ ํ์์ค pop |
| 32 | + if rooms and rooms[0] <= s: |
| 33 | + heapq.heappop(rooms) |
| 34 | + |
| 35 | + # ํ์ฌ ํ์ push |
| 36 | + heapq.heappush(rooms, e) |
| 37 | + |
| 38 | + return len(rooms) |
| 39 | + |
| 40 | + def minMeetingRooms(self, intervals: List[List[int]]) -> int: |
| 41 | + """ |
| 42 | + [Complexity] |
| 43 | + - TC: O(nlogn) |
| 44 | + - SC: O(n) |
| 45 | +
|
| 46 | + [Approach] |
| 47 | + start์ end๋ฅผ ๋๋์ด ์ ๋ ฌํ๋ค๋ฉด, ๊ฐ๊ฐ์ ์์๋ฅผ ๊ฐ๋ฆฌํค๋ two-pointer๋ฅผ ์ด์ฉํด |
| 48 | + ํ์์ค์ ์ฌ์ฌ์ฉํ ์ ์๋ ๊ฒฝ์ฐ์ ์๋ก์ด ํ์์ค์ด ํ์ํ ๊ฒฝ์ฐ๋ฅผ ํ๋จํ ์ ์๋ค. |
| 49 | + starts๋ฅผ ์ํํ๋ฉด์ e๋ผ๋ pointer๋ก ends์ ์ฒซ๋ฒ์งธ ์์๋ถํฐ ๋น๊ตํ๋ฉด ๋ค์๊ณผ ๊ฐ์ด ์ผ์ด์ค๋ฅผ ๋๋ ์ ์๋ค. |
| 50 | + - non-overlap(ends[e] <= s): ํ์์ค ์ฌ์ฌ์ฉ ๊ฐ๋ฅ (e++๋ฅผ ํตํด ๋ค์ ํ์ ์ดํด๋ณด๊ธฐ) |
| 51 | + - overlap(ends[e] > s): ์๋ก์ด ํ์์ค ํ์ |
| 52 | + """ |
| 53 | + starts = sorted(s for s, _ in intervals) |
| 54 | + ends = sorted(e for _, e in intervals) |
| 55 | + |
| 56 | + res = e = 0 |
| 57 | + |
| 58 | + for s in starts: |
| 59 | + # non overlap -> ํ์์ค ์ฌ์ฌ์ฉ ๊ฐ๋ฅ (๋ค์ ํ์ ์ดํด๋ณด๊ธฐ) |
| 60 | + if ends[e] <= s: |
| 61 | + e += 1 |
| 62 | + # overlap -> ์๋ก์ด ํ์์ค ํ์ |
| 63 | + else: |
| 64 | + res += 1 |
| 65 | + |
| 66 | + return res |
0 commit comments