Sort and then merge: python version


  • 0
    B
    class Solution:
    # @param intervals, a list of Interval
    # @return a list of Interval
    
        
    def merge(self, intervals):
        
        def getkey(obj):
            return obj.start
            
        # sort the object list by key 
        if len(intervals)<=1:
            return intervals
        
        intervals.sort(key=getkey)
        
        start=intervals[0].start
        end=intervals[0].end
        
        merge=[]
        
        for index in range(1,len(intervals)):
            if intervals[index].start>end:
                merge.append(Interval(start,end))
                start=intervals[index].start
                end=intervals[index].end
            elif intervals[index].start<=end:
                if intervals[index].end>end:
                    end=intervals[index].end
        
        merge.append(Interval(start,end))
        
        return merge
    

    here is a simple version of python that uses getkey() to sort the intervals by the start point of each. then the merge becomes easy


Log in to reply
 

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