Merging Overlapping Intervals

前端 未结 4 2040
花落未央
花落未央 2020-12-10 14:31

Currently, I have intervals of:

temp_tuple = [[-25, -14], [-21, -16], [-20, -15], [-10, -7], [-8, -5], [-6, -3], [2, 4], [2, 3], [3, 6], [12, 15], [13, 18],          


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 14:52

    The salient feature of the solution below is to run a list called final parallel to the input list. Before entering the for loop, the final list inserts the first array item in it. Then starts the comparison. That's it!

    def merger(a):
    
        final=[]
    
        final.append(a[0])
    
        for i in range(1,len(a)):
    
            if a[i][0]<=final[-1][1]:
    
               if a[i][1]>final[-1][1]:
    
                   low_limit=final[-1][0]
                   hi_limit=a[i][1]
                   final.pop()
                   final.append([low_limit,hi_limit])
    
               if a[i][1]<=final[-1][1]:
    
                    low_limit=final[-1][0]
                    hi_limit=final[-1][1]
                    final.pop()
                    final.append([low_limit,hi_limit])
    
              if final[-1][0]

    Output:

    [[-25, -14], [-10, -3], [2, 6], [12, 18], [22, 30]]
    

提交回复
热议问题