Python iterative solution


  • 0
    G
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """
        if not intervals:
            return []
        res = []
        
        intervals.sort(key = lambda x: x.start)
        
        i = 0
        while i < len(intervals):
            if i == len(intervals) - 1 or intervals[i].end < intervals[i+1].start:
                res.append(intervals[i])
            else:
                intervals[i+1].start = intervals[i].start
                intervals[i+1].end = max(intervals[i+1].end, intervals[i].end)
            i += 1
        
        return res

Log in to reply
 

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