56. 合并区间
难度中等215收藏分享切换为英文关注
通过次数
37,436
提交次数
95,681
题目描述
评论 (344)
题解(93)New
提交记录
给出一个区间的集合,请合并所有重叠的区间。
示例 1:
输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:
输入: [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
先排序,再合并,这段代码写的不好,效率有点低呢....
#include
#include
#include
using namespace std;
class Solution{
public:
vector> merge(vector> &intervals){
sort(intervals.begin(),intervals.end(),cmp_func); /* 排序 */
for(int i=1;i tempfront = intervals[i-1];
vector temp = intervals[i];
int Last;
if(temp.front() <= tempfront.back()){
if(temp.back() > tempfront.back()){
Last = temp.back();
}else{
Last = tempfront.back();
}
cout<<"temp.front:"<> &intervals){
cout<<"new:"<>::iterator CurArr = intervals.begin();
while(CurArr!=intervals.end()){
cout<<"arr:";
vector::iterator it = (*CurArr).begin();
while(it!=(*CurArr).end()){
cout<<*it<<" ";
it++;
}
cout< &x1, vector &x2){
int first = x1.front();
int second = x2.front();
return (first < second);
}
};
/* [1,4],[0,2],[3,5] */
/*
* 输入:[[2,3],[2,2],[3,3],[1,3],[5,7],[2,2],[4,6]]
* 输出:[[4,6],[4,7]]
* 预期:[[1,3],[4,7]]
*/
/* * 输入:
*
* [[1,3],[2,2],[2,2],[2,3],[3,3],[4,6],[5,7]]
* [[1,3],[2,2],[2,3],[3,3],[4,6],[5,7]]
* [[1,3],[2,3],[3,3],[4,6],[5,7]]
* [[1,3],[3,3],[4,6],[5,7]]
*
*
*/
int main(){
// vector a1 = {15,18};
// vector a2 = {8,10};
// vector a3 = {1,3};
// vector a4 = {2,6};
// vector a1 = {3,5};
// vector a2 = {0,2};
// vector a3 = {1,4};
vector> arr = {
{2,3},{2,2},{3,3},{1,3},{5,7},{2,2},{4,6}};
// arr.push_back(a1);
// arr.push_back(a2);
// arr.push_back(a3);
// arr.push_back(a4);
Solution* ps = new Solution();
vector> intervals = ps->merge(arr);
return 0;
}