Saturday, June 7, 2014

Leetcode (Python): Merge Intervals

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].

Solution:

# Definition for an interval.
# class Interval:
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution:
    # @param intervals, a list of Interval
    # @return a list of Interval
    def merge(self, intervals):
        intervals = self.mergeSort(intervals)
        i  =1
        while i< len(intervals):
            if intervals[i-1].end >= intervals[i].start:
                intervals[i-1].end = max(intervals[i-1].end, intervals[i].end)
                intervals.pop(i)
            else:
                i +=1
        return intervals
        
        
    def mergeSort(self, intervals):
        if len(intervals)<=1:
            return intervals
            
        left = self.mergeSort(intervals[0:len(intervals)//2])
        right = self.mergeSort(intervals[len(intervals)//2:len(intervals)])
        return self.mergeList(left, right)
        
    def mergeList(self, list1, list2):
        solution = []
        pointer1 = 0
        pointer2 = 0
        while pointer1 < len(list1) and pointer2<len(list2):
            if list1[pointer1].start< list2[pointer2].start:
                solution.append(list1[pointer1])
                pointer1 += 1
            else:
                solution.append(list2[pointer2])
                pointer2 += 1
        while pointer1 < len(list1):
            solution.append(list1[pointer1])
            pointer1 += 1
        while pointer2 < len(list2):
            solution.append(list2[pointer2])
            pointer2 += 1
        return solution

No comments :

Post a Comment