Merge Intervals 合并区间

本文深入探讨了一种用于合并重叠区间的数据结构算法。通过定义结构体Item存储区间的开始和结束点,实现了基于开始点排序的比较函数cmp,并提供了一个maxT函数用于返回两个整数中的较大者。核心部分是MergeIntervals函数,它接收一个包含Item的向量作为输入,通过迭代检查和更新当前区间的结束点来合并重叠区间,最终返回合并后的区间向量。代码中还展示了如何使用sort函数进行排序,以及如何调用MergeIntervals函数并打印结果。

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

#include
#include
#include
using namespace std;
struct Item
{
int start;
int end;
};
bool cmp(Item &it1, Item &it2)
{
return it1.start<it2.start;
}
int maxT(int a, int b)
{
if (a > b)
{
return a;
}
return b;
}
vector MergeIntervals(vector &vectItem)
{
vector res;
int start = vectItem[0].start;
int end = vectItem[0].end;
for (int i = 1; i < vectItem.size(); i++)
{
if (end < vectItem[i].start)
{
res.push_back({ start,end });
start = vectItem[i].start;
end = vectItem[i].end;
}
else
{
end = maxT(end, vectItem[i].end);
}

}
res.push_back({ start,end });
return res;

}
int main()
{
//vector vectItem{ {1,3},{2,6},{8,10},{15,18},{7,9},{12,14} };
vector vectItem{ {1,4},{4,6} };
sort(vectItem.begin(), vectItem.end(), cmp);
vector vecitems = MergeIntervals(vectItem);
system(“pause”);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值