本文主要是介绍Leet Code OJ 56. Merge Intervals [Difficulty: Medium] -Python,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
56. Merge Intervals
【Medium】
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
Constraints:
intervals[i][0] <= intervals[i][1]
题意:区间合并
思路:
1.首先给区间排序
2.判断当前区间右是否是比下一个相邻区间左大,若大则合并加入列表,并且删除当前区间;否则,将当前区间加入列表中
代码:
#56
class Solution:def merge(self, intervals):if len(intervals)==1 or len(intervals)==0:return intervalsnew_list = []intervals.sort()new_list.append([intervals[0][0],intervals[0][1]])j = 0for i in range(1,len(intervals)):if new_list[j][1] >= intervals[i][0]:new_list.append([min(new_list[j][0],intervals[i][0]),max(new_list[j][1],intervals[i][1])])del new_list[-2]else:new_list.append([intervals[i][0],intervals[i][1]])j = j + 1return new_list
这篇关于Leet Code OJ 56. Merge Intervals [Difficulty: Medium] -Python的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!