Published:
Updated:

  • ํ˜„์žฌ ๊ตฌ๊ฐ„๊ณผ ๋งˆ์ง€๋ง‰ ๊ตฌ๊ฐ„์˜ ๋น„๊ต๋ฅผ ์–ด๋–ป๊ฒŒ ํ•˜๋Š๋ƒ์˜ ๋ฌธ์ œ์ž„


Solution

from typing import List


class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        answer: List[List[int]] = []

        intervals.sort(key=lambda x: x[0])

        for interval in intervals:
            # ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ: answer, ํ˜„์žฌ ๊ตฌ๊ฐ„: inverval[0]
            # ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋น„์–ด ์žˆ๊ฑฐ๋‚˜
            # ํ˜„์žฌ ๊ตฌ๊ฐ„์ด answer์˜ ๋งˆ์ง€๋ง‰ ๊ตฌ๊ฐ„๊ณผ ๊ฒน์น˜์ง€ ์•Š๋Š”๋‹ค๋ฉด
            # ํ˜„์žฌ ๊ตฌ๊ฐ„์„ ๊ทธ๋Œ€๋กœ answer์— ์ถ”๊ฐ€
            if not answer or interval[0] > answer[-1][1]:
                answer.append(interval)
                continue

            # continue์— ์•ˆ ๊ฑธ๋ ธ์œผ๋‹ˆ ๊ฒน์น˜๋Š” ๊ตฌ๊ฐ„์ด ์žˆ๋‹ค๋Š” ๋œป -> ํ˜„์žฌ ๊ตฌ๊ฐ„๊ณผ answer์˜ ๋งˆ์ง€๋ง‰ ๊ตฌ๊ฐ„์„ ๋ณ‘ํ•ฉํ•˜๋ฉด ๋จ
            # answer์˜ ๋งˆ์ง€๋ง‰ ๊ตฌ๊ฐ„์˜ ๋ ๊ฐ’ vs ํ˜„์žฌ ๊ตฌ๊ฐ„์˜ ๋ ๊ฐ’
            # ์ด๊ฒƒ์„ ๋น„๊ตํ•˜์—ฌ ๋” ํฐ ๊ฐ’์ด ๋์— ์˜ค๋Š” ๊ฒƒ์ด ๋งž์œผ๋ฏ€๋กœ ๊ทธ๊ฑธ๋กœ ์„ ํƒ
            answer[-1][1] = max(answer[-1][1], interval[1])

        return answer


Reference

Leave a comment