코딩 연습/Python

[leetcode] 56. Merge Intervals

썬2 2022. 3. 14. 19:30

Question

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

 

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

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

        merged = []
        for interval in intervals:
            # if the list of merged intervals is empty or if the current
            # interval does not overlap with the previous, simply append it.
            if not merged or merged[-1][1] < interval[0]:
                merged.append(interval)
            else:
            # otherwise, there is overlap, so we merge the current and previous
            # intervals.
                merged[-1][1] = max(merged[-1][1], interval[1])

        return merged

'코딩 연습 > Python' 카테고리의 다른 글

[leetcode] 121. Best Time to Buy and Sell Stock  (0) 2022.03.14
[HackerRank] Between Two Sets  (0) 2022.02.12
백준_9020: 골드바흐의 추측  (0) 2022.02.05
백준_11508: 2+1 세일  (0) 2022.02.03
백준_11657: 타임머신  (0) 2022.01.30