题目如下:给定一个源区间[x,y]和N个无序的目标区间[x1,y1] [x2,y2] … [xn,yn],判断源区间[x,y]是不是在目标区间内
思路:先对现有目标区间数组进行预处理,即先对目标区间按照开始时间进行排序,然后合并能合并的区间,最后用二分查找在合并后的区间中判断
时间复杂度分析:
排序为O(N*lgN),合并的时间为O(N),查找的时间为O(lgN),所以总的时间复杂度为O(N*lgN)
代码如下:
//============================================================================ // Name : Intervals.cpp // Author : Jimmy Cai // Version : // Description : 区间重合判断 //============================================================================ #include <vector> #include <algorithm> #include <iostream> using namespace std; /** * 表示区间 */ struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; class Intervals { private: vector<Interval> result;//保存排序合并后的区间结果 //类的成员函数指针其实不是指针 static bool Less(const Interval &i1, const Interval &i2){ return i1.start < i2.start; } /** * 合并函数 */ vector<Interval> merge(vector<Interval> &intervals) { if(intervals.size() == 0) return result; sort(intervals.begin(), intervals.end(), Less);//stl提供的vector排序 int start = intervals.begin()->start; int end = intervals.begin()->end; for(vector<Interval>::iterator iter = intervals.begin(); iter != intervals.end(); iter++){ if(iter->end > end) end = iter->end; if(iter != intervals.end() - 1 && end >= (iter+1)->start) ; else{ result.push_back(Interval(start, end)); if(iter != intervals.end() - 1){ start = (iter+1)->start; end = (iter+1)->end; } } } return result; } public: /** * 用二分查找 */ bool find(Interval target, vector<Interval> &intervals) { result = merge(intervals); int size = result.size(); int begin = 0; int end = size - 1; int mid; while(begin <= end){ mid = (end - begin) >> 1; if(target.start >= result[mid].start && target.end <= result[mid].end) return true; if(target.end < result[mid].start) end = mid; else if(target.start > result[mid].end) begin = mid; else return false; } return false; } }; /** * 测试 */ int main() { Intervals mainProcess; Interval target(5,9); Interval inter1(2,6); Interval inter2(1,4); Interval inter3(6,8); Interval inter4(8,15); vector<Interval> intervals; intervals.push_back(inter1); intervals.push_back(inter2); intervals.push_back(inter3); intervals.push_back(inter4); cout << "Result:" << mainProcess.find(target, intervals) << endl; return 0; }