[Leetcode 56] Merge Intervals

이재윤·2025년 1월 21일

https://leetcode.com/problems/merge-intervals/description/

1) 코드

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

        answer = [] 
        intervals.sort(key=lambda x:(x[0], x[1]))
        
        currStart = intervals[0][0]
        currEnd = intervals[0][1]

        for i in range(1, len(intervals)):
            start = intervals[i][0]
            end = intervals[i][1] 

            if currEnd >= start:
                currStart = min(currStart, start)
                currEnd = max(currEnd, end) 
                continue
            else:
                answer.append([currStart, currEnd])
                currStart = start
                currEnd = end 

        answer.append([currStart, currEnd])
        
        return answer 

2) 해설

  • 첫 번째꺼 기준으로 오름차순 정렬을 해준뒤에,
    병합 조건에 따라, 병합해나가면 된다.

0개의 댓글