LeetCode 56 LintCode 156 – Python 3 (Week 09 – 04)

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        ans = []
        
        for interval in sorted(intervals, key = lambda x: x[0]):
            if len(ans) == 0 or ans[-1][1] < interval[0]:
                ans.append(interval)
            else:
                ans[-1][1] = max(ans[-1][1], interval[1])
                
        return ans

Time complexity is O(nlogn): sorted(). Space complexity is O(1).

Leave a comment

Design a site like this with WordPress.com
Get started