Leetcode: Merge Intervals

Merge Intervals



Similar Problems:


Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## Blog link: https://code.dennyzhang.com/merge-intervals
## Basic Ideas: Search by the starting values
##
## Complexity: Time O(n*log(n)), Space O(n)
class Solution(object):
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """
        ret = []
        for entry in sorted(intervals, key=lambda entry: entry.start):
            if ret and entry.start <= ret[-1].end:
                ret[-1].end = max(ret[-1].end, entry.end)
            else:
                ret.append(entry)
        return ret
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.