描述
Given a collection of intervals, merge all overlapping intervals.
For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18]
Given a collection of intervals, merge all overlapping intervals.
For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18]
#include<iostream>
#include<vector>
#include<map>
using namespace std;
vector<pair<int, int>>InsertInterval(vector<pair<int, int>> input, pair<int, int> data)
{
vector<pair<int, int>> res;
if (input.size() <= 0)
{
res.push_back(data);
return res;
}
//===
int length = input.size();
pair<int, int> insert;
//===
int i = 0;
for (; i < length; i++)
{
if (data.first < input[i].first)
{
insert.first = data.first;
break;
}
else if (input[i].first <= data.first&&data.first <= input[i].second)
{
insert.first = input[i].first;
break;
}
else if (input[i].second < data.first)
{
res.push_back(input[i]);
}
}
//===
if (i >= length)
{
res.push_back(data);
return res;
}
//===
int j = i;
for (; j < length; j++)
{
if (data.second < input[j].first)
{
insert.second = data.second;
res.push_back(insert);
for (int k = j; k < length; k++)
{
res.push_back(input[k]);
}
break;
}
else if (input[j].first <= data.second&&data.second <= input[j].second)
{
insert.second = input[j].second;
res.push_back(insert);
for (int k = j + 1; k < length; k++)
{
res.push_back(input[k]);
}
break;
}
else if (data.second > input[length - 1].second)
{
insert.second = data.second;
res.push_back(insert);
break;
}
}
return res;
}
vector<pair<int, int>>InsertIntervals(vector<pair<int, int>> input)
{
if (input.size() <= 0)
return input;
vector<pair<int, int>> res;
res.push_back(input[0]);
for (int i = 1; i < input.size(); i++)
{
res = InsertInterval(res, input[i]);
}
return res;
}
int main()
{
//===
vector<pair<int, int>> input;
input.push_back(make_pair(1, 3));
input.push_back(make_pair(2, 6));
input.push_back(make_pair(8, 10));
input.push_back(make_pair(15, 18));
//===
vector<pair<int, int>>res = InsertIntervals(input);
for (int i = 0; i < res.size(); i++)
{
cout << res[i].first << " " << res[i].second << endl;
}
}