Short python with only one loop, similar method as "Merge Interval".


  • 0
    W
    class Solution(object):
        def insert(self, intervals, newInterval):
            #ok: true means newInterval was already inserted
            ans, ok, i= [], False, 0
            while i < len(intervals) or not ok:
                candi = None
                if i == len(intervals) or (not ok and newInterval.start <= intervals[i].start):
                    candi = newInterval
                    ok = True
                else:
                    candi = intervals[i]
                    i += 1
                if ans and candi.start <= ans[-1].end:
                    ans[-1].end = max(ans[-1].end, candi.end)
                else:
                    ans.append(candi)
            return ans
    

Log in to reply
 

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