/*
需求示意:
已知有M段不连续的时间段,[t1,t2],[t2,t3],[t3,t4],[t6,t7],[t7,t8],[t9,t10]
合并后应为:[t1,t4],[t6,t8],[t9,t10],则缺失[t4,t5]的时间段。
条件:时间段前后为闭包,
目的:将满足条件的零碎片段拼接为一段连续的大片段,并输出拼接后的片段.
*/
struct TyTime
{
int start;
int end;
};
vector<TyTime> merge(vector<TyTime>& m_vcTyTime)
{
if (m_vcTyTime.size() <= 1)
{
return m_vcTyTime;
}
vector<TyTime> res;
//排序,按开始时间从小到大
sort(m_vcTyTime.begin(), m_vcTyTime.end(), [](TyTime a, TyTime b){return a.start < b.start; });
int i = 0;
TyTime temp = { m_vcTyTime[0].start, m_vcTyTime[0].end };
while (i < m_vcTyTime.size())
{
temp.start = m_vcTyTime[i].start;
temp.end = m_vcTyTime[i].end;
while (i < m_vcTyTime.size())
{
//注意数组越界
if (i < m_vcTyTime.size() - 1 && temp.end >= m_vcTyTime[i + 1].start)
{
if (temp.end < m_vcTyTime[i + 1].end)
{
temp.end = m_vcTyTime[i + 1].end;
}
i++;
}
else
{
i++;
break;
}
}
res.push_back(temp);
}
return res;
}
void main()
{
vector<TyTime>t1{ { 1, 2 }, { 2, 3 }, { 3, 4 }, { 5, 6 }, { 6, 7 }, { 8, 9 } };
cout << "合并前:\n";
for (auto node : t1)
{
cout << "[" << node.start << "," << node.end << "],";
}
cout << endl;
cout << "合并后:\n";
vector<TyTime>t2 = merge(t1);
for (auto node : t2)
{
cout << "[" << node.start << "," << node.end << "],";
}
cout << endl;
system("pause");
}
结果: