Problem: 56. 合并区间
文章目录
- 思路
- Code
思路
对数组排序,按照左端点从小到大排序。初始化Merged,将第一个区间放入。遍历intervals ,如果当前区间的左端点比merged最后一个区间的右端点大,不重合,直接将该区间加入最后,否则,重合,更新最后一个区间的右端点。
Code
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
// 合并区间
int n = intervals.size() ;
sort(intervals.begin() , intervals.end()) ;
vector<vector<int>> merged ;
merged.push_back(intervals[0]) ;
int r = intervals[0][1] ;
for(int i = 1 ; i<intervals.size() ; i++) {
int start = intervals[i][0] ;
int end = intervals[i][1] ;
// 如果当前的左端点小于之前的右,不重合
if(start > r) {
merged.push_back({start,end}) ;
}else{
// 否则,重合,更新右端点
merged.back()[1] = max(merged.back()[1] ,end) ;
}
r = merged.back()[1] ;
}
return merged ;
}
};
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# 合并区间
intervals.sort() # Sort the intervals based on their start points
merged = [intervals[0]]
r = intervals[0][1]
for i in range(1, len(intervals)):
start, end = intervals[i]
# If the current interval's start is greater than the previous interval's end, they don't overlap
if start > r:
merged.append([start, end])
else:
# Otherwise, they overlap, update the end point of the merged interval
merged[-1][1] = max(merged[-1][1], end)
r = merged[-1][1]
return merged