使用C ++合并重叠间隔。
问题陈述
给定一组任意时间间隔的时间,将所有重叠的时间间隔合并为一个并输出结果,该结果应仅具有互斥的时间间隔
给定间隔集为{{12,14},{11,13},{20,22},{21,23}},则
间隔{12,14}和{11,13}彼此重叠,因此将它们合并为{11,14}
间隔{20,22}和{21,23}彼此重叠,因此将它们合并为{20,23}
算法
1. Sort the intervals based on increasing order of starting time 2. Push the first interval on to a stack 3. For each interval perform below steps: 3.1. If the current interval does not overlap with the top of the stack, push it. 3.2. If the current interval overlaps with top of the stack and ending time of current interval is more than that of top of stack, update stack top with the ending time of current interval. 4. Finally, stack contains the merged intervals.
示例
#include <iostream>
#include <algorithm>
#include <stack>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
struct interval{
int start;
int end;
};
bool compareInterval(interval i1, interval i2){
return (i1.start < i2.start);
}
void mergeOverlappingIntervals(interval *arr, int n){
if (n <= 0) {
return;
}
stack<interval> s;
sort(arr, arr + n, compareInterval);
s.push(arr[0]);
for (int i = 1; i < n; ++i) {
interval top = s.top();
if (top.end < arr[i].start) {
s.push(arr[i]);
} else if(top.end < arr[i].end) {
top.end = arr[i].end;
s.pop();
s.push(top);
}
}
cout << "Merged intervals: " << endl;
while (!s.empty()) {
interval i = s.top();
cout << "{" << i.start << ", " << i.end << "}" << " ";
s.pop();
}
cout << endl;
}
int main(){
interval arr[] = {{12, 14}, {11, 13}, {20, 22}, {21, 23}};
mergeOverlappingIntervals(arr, SIZE(arr));
return 0;
}输出结果
当您编译并执行上述程序时。它生成以下输出-
Merged intervals:
{20, 23} {11, 14}热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿