Leetcode - 56. Merge Intervals

문제

Loading...
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

정답

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals = sorted(intervals, key=lambda x: x[0])
        result = []
        
        while intervals:
            left, right = intervals.pop(0)
            
            if not result:
                result.append([left, right])
            else:
                pre = result[-1]
                if pre[0] <= left <= pre[1]:
                    result[-1] = [min(left, pre[0]), max(right, pre[1])]
                else:
                    result.append([left, right])

        return result