Two line to solve this problem.


  • -12
    L

    There is another question called Merge Interval.
    I think it's better to solve the merge question first.

    With the merge solution ,you can use two lines to solve this problem:

    class Solution:
    
    # @param intervals, a list of Interval
    # @return a list of Interval
    def merge(self, intervals):
        if(len(intervals)<2):return intervals;
    
        result=[i for i in intervals];
        result.sort(key=lambda itv:itv.start);
    
        hasMerge=True;
        while(hasMerge):
            hasMerge=False;
            i=0;
            while(i<len(result)-1):
                if(result[i].end >= result[i+1].start):
                    hasMerge=True;
                    if(result[i].end < result[i+1].end):
                        result[i].end=result[i+1].end;
                    del result[i+1];
                    i-=1;
                i+=1;
        return result;
    
    # @param intervals, a list of Intervals
    # @param newInterval, a Interval
    # @return a list of Interval
    def insert(self, intervals, newInterval):
        intervals.append(newInterval);
        return self.merge(intervals)

  • 0
    J

    “Two line to solve this problem.” is really a bad title.


Log in to reply
 

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