[LeetCode] Merge Intervals

本文介绍了一种解决区间合并问题的有效算法。首先按起始位置对区间进行排序,然后依次扫描并合并重叠区间。文中详细解释了比较函数、判断区间是否重叠及合并两个重叠区间的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The idea to solve this problem is to first sort the intervals according to their start field and then scan the intervals from head to tail and merge those that overlap.

For sorting the intervals according to their start field, we define a comparison function as follows.

1 static bool comp(Interval interval1, Interval interval2) {
2     return interval1.start < interval2.start;
3 }

Then all the intervals are sorted in the ascending order of start. Now we define a current intervalcur and initialize it to be intervals[0]. Then we scan from intervals[1] to intervals[n - 1]. If it overlaps with cur, merge them; otherwise, add cur to res, update cur to be intervals[i]and move on with the merging process.

There are two required subroutines in the above process: isOverlap to tell whether two intervals overlap and mergeTwo to merge two overlapping intervals.

For isOverlap, since the intervals are sorted in ascending order of start, we simply need to guarantee that end of the left (with smaller start) interval is not less than start of the right (with larger start) interval.

For mergeTwo, just take the minimum of start and maximum of end of the two overlapping intervals and return a new interval with these two values.

The complete code is as follows, which should be self-explanatory.

 1 class Solution {
 2 public:
 3     vector<Interval> merge(vector<Interval>& intervals) {
 4         vector<Interval> res;
 5         if (intervals.empty()) return res;
 6         sort(intervals.begin(), intervals.end(), comp);
 7         Interval cur(intervals[0].start, intervals[0].end);
 8         for (int i = 1, n = intervals.size(); i < n; i++) {
 9             if (isOverlap(cur, intervals[i]))
10                 cur = mergeTwo(cur, intervals[i]);
11             else {
12                 res.push_back(cur);
13                 cur = intervals[i];
14             }
15         }
16         res.push_back(cur);
17         return res;
18     }
19 private:
20     static bool comp(Interval interval1, Interval interval2) { 
21         return interval1.start < interval2.start;
22     }
23     bool isOverlap(Interval interval1, Interval interval2) {
24         return interval1.end >= interval2.start;
25     }
26     Interval mergeTwo(Interval interval1, Interval interval2) {
27         int start = min(interval1.start, interval2.start);
28         int end = max(interval1.end, interval2.end);
29         return Interval(start, end);
30     }
31 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4616854.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值