Description:
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].
Solution:
Analysis and Thinking:
分析題目的要求可得,問題要求獲得輸入的一組由若干數組組成的數組集合,將其中有重疊的元素進行合併。解決方法應該分爲兩步:一是找到相鄰間隔,二是查看元素是否有重疊,並將重疊的元素合併。這裏,首先需要依據間隔的起始時間對輸入數組排序,然後遍歷輸入,判斷是否有重疊的依據是,若當前一個間隔的結束時間大於等於其開始時間,則有重疊,需要合併。
Steps:
1.將數組集合中的第一個間隔拷貝到新的數組中,該數組爲待返回結果數組
2.從輸入的第二個元素開始,遍歷輸入,重複3、4
3.查看是否有重疊情況,若有,改變結果數組的最後元素的結束時間
4.若無重疊情況,將輸入的結合的該元素添加入結果數組
5.返回結果數組
Codes:
bool compare(Interval in1,Interval in2)
{
if in1.start<in2.start
return 1;
else
return 0;
}
class Solution
{
public:
vector<Interval> merge(vector<Interval> &intervalsInput)
{
vector<Interval> result_tempi;
if(intervalsInput.size()==0)
return result_tempi;
sort(intervalsInput.begin(),intervalsInput.end(),compare);
result_tempi.push_back(intervalsInput[0]);
for(int i=1;i<intervalsInput.size();i++)
{
if(result_tempi[result_tempi.size()-1].end >=intervalsInput[i].start)
result_tempi[result_tempi.size()-1].end=max(result_tempi[result_tempi.size()-1].end,intervalsInput.end);
else
result_tempi.push_back(intervalsInput[i]);
}
return result_tempi;
}
};
Results: