intervals_sol

mail@pastecode.io avatar
unknown
python
2 years ago
873 B
11
Indexable
Never
class Solution(object):
    def merge(self, intervals):
        """
        :type intervals: List[List[int]]
        :rtype: List[List[int]]
        """
        # 1. Sort array according to the 1st element 
        intervals_sorted = sorted(intervals, key=lambda x: x[0])
        
        # 2. Loop over it and store result in a new array
        start_ = intervals_sorted[0][0]
        end_ = intervals_sorted[0][1]
        results = []
        
        for interval in intervals_sorted[1:]:
            if interval[0] <= end_ and interval[1] >= end_:
                end_ = interval[1]
            else:
                if interval[1] < end_:
                    continue
                results.append([start_, end_])

                start_ = interval[0]
                end_ = interval[1]
        
        results.append([start_, end_])
        
        return results