Short python solution


  • 13
    F

    Sort the list first. Check if the new interval overlaps with the previous one in the output list. If yes, update it. Otherwise, append the new one.

    class Solution(object):
        def merge(self, intervals):
            """
            :type intervals: List[Interval]
            :rtype: List[Interval]
            """
            if len(intervals) == 0: return []
            intervals = sorted(intervals, key = lambda x: x.start)
            res = [intervals[0]]
            for n in intervals[1:]:
                if n.start <= res[-1].end: res[-1].end = max(n.end, res[-1].end)
                else: res.append(n)
            return res

  • 0

    @Froxie How did you come up with this solution?
    Would you like to share your thought process!


  • 0
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.