一、题目描述
给定多个可能重叠的区间,找出重叠区间的个数。
举例如下:
输入:[1,5],[10,15],[5,10],[20,30]
输出:2
说明:题意应该是找出重叠区间中区间的最大个数,当没有区间重叠时,重叠个数最大为1,比如
输入为:[1,5],[10,15],则输出为1;
输入为:[1,2],[2,3],[3,4],[4,5],则输出为2(重叠区间相互之间都要有交集);
输入为:[1,7],[2,5],[3,4],[8,15],[9,17],[20,25],则输出为3。
二、题目分析
此题解题方法比较简单,只要将区间分隔成各个点,每个点有两个属性,一个是值,一个是标志(0起点,1止点),然后对这些点排序,最后,从头开始扫描排序的结果,遇到起点重叠个数加1,遇到止点重叠个数减1,并且记录好重叠个数的最大值。
本算法的时间复杂度为O(nlogn),因为算法时间主要消耗在排序上。
三、算法实现
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <cmath>
- #include <Windows.h>
- using namespace std;
-
-
-
- class Interval
- {
- public:
- Interval( int iStart, int iEnd)
- :m_iStart( iStart), m_iEnd(iEnd){}
- int m_iStart;
- int m_iEnd;
- };
-
- typedef vector<Interval> IntervalVec;
-
-
-
- class PointComparable
- {
- public:
- PointComparable( int iVal, int iType )
- :m_iVal( iVal ), m_iType( iType ){}
-
-
- bool operator < ( const PointComparable& pcPoint )
- {
- if ( this->m_iVal == pcPoint.m_iVal )
- {
- return this->m_iType < pcPoint.m_iType;
- }
- return this->m_iVal < pcPoint.m_iVal;
- }
-
- int m_iVal;
- int m_iType;
- };
-
- int GetOverlappedIntervalMaxCount( const IntervalVec& intvVec )
- {
- vector<PointComparable> pcVec;
- for ( IntervalVec::const_iterator it = intvVec.begin();
- it != intvVec.end(); ++it )
- {
- pcVec.push_back( PointComparable( it->m_iStart, 0 ) );
- pcVec.push_back( PointComparable( it->m_iEnd, 1 ) );
- }
-
- sort( pcVec.begin(), pcVec.end() );
-
-
-
- int iMaxCount = 0;
- int iCurCount = 0;
- for ( vector<PointComparable>::iterator itTemp = pcVec.begin();
- itTemp != pcVec.end(); ++itTemp )
- {
- cout << itTemp->m_iVal << " " << itTemp->m_iType << endl;
- if ( itTemp->m_iType == 0 )
- {
- iCurCount++;
- iMaxCount = __max( iCurCount, iMaxCount );
- }
- else
- {
- iCurCount--;
- }
- }
-
- return iMaxCount;
- }
-
- int main()
- {
- IntervalVec intvVec;
-
-
-
-
-
-
-
-
-
-
- intvVec.push_back( Interval(1,2) );
- intvVec.push_back( Interval(2,3) );
- intvVec.push_back( Interval(3,4) );
- intvVec.push_back( Interval(4,5) );
-
-
-
-
- cout << "最大重叠区间个数:" << GetOverlappedIntervalMaxCount( intvVec )
- <span style="white-space:pre"> </span>cout << endl;
- return 0;
- }
系列文章说明:
1.本系列文章[算法练习],仅仅是本人学习过程的一个记录以及自我激励,没有什么说教的意思。如果能给读者带来些许知识及感悟,那是我的荣幸。
2.本系列文章是本人学习陈东锋老师《进军硅谷,程序员面试揭秘》一书而写的一些心得体会,文章大多数观点均来自此书,特此说明!
3.文章之中,难免有诸多的错误与不足,欢迎读者批评指正,谢谢.