一系列无序的区间,且每个区间有自己的属性,现在要求合并重叠,并且属性相同的区间。
为演示算法设计如下数据结构:
class Range{ public: Range() { m_s = -1; m_e = -1; m_t = -1; } Range(int s, int e, int t) { m_s = s; m_e = e; m_t = t; } ~Range(){} Range& operator=(const Range& other) { m_s = other.m_s; m_e = other.m_e; m_t = other.m_t; return *this; } int m_s; int m_e; int m_t; };
首先将这些无序区间按起始位置进行排序,这里使用最简单的冒泡排序:
void Sort(vector<Range>& ranges) { for (size_t m = 0; m < ranges.size(); m++) { for (size_t n = 0; n < ranges.size() - m - 1; n++) { if (ranges[n].m_s > ranges[n+1].m_s) { Range tmp = ranges[n]; ranges[n] = ranges[n+1]; ranges[n+1] = tmp; } } } }
合并算法如下:
void Merge(vector<Range>& ranges) { if (ranges.size() < 2) { return; } vector<Range>::iterator iter = ranges.begin(); Range r = *iter; vector<Range> tmp; tmp.push_back(r); iter++; for (; iter != ranges.end(); iter++) { if (r.m_t != iter->m_t) { r = *iter; tmp.push_back(r); continue; } if (r.m_e < iter->m_s) { r = *iter; tmp.push_back(r); continue; } if (r.m_e < iter->m_e) { r.m_e = iter->m_e; tmp[tmp.size()-1] = r; } } ranges.swap(tmp); }