感觉有一点进步了,但是思路还是不够犀利。
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> merge(vector<Interval>& intervals) { vector<pair<int,int>> r; for(int i=0;i<intervals.size();i++) r.push_back(make_pair(intervals[i].start,intervals[i].end)); sort(r.begin(),r.end()); int index=0; vector<Interval> res; while(index<r.size()){ int start=r[index].first; int end=r[index].second; if(start == INT_MAX) { index++; continue; } for(int i=index+1;i<r.size();i++) { if(r[i].first == end){ end=r[i].second; r[i].first=INT_MAX,r[i].second=INT_MAX; } } while(r[index+1].first >= start && r[index+1].second<=end && r[index+1].second>=start&&r[index+1].second<=end) { index++; } while(end>=r[index+1].first && end<=r[index+1].second && index+1 <=r.size()) { index++; end=r[index].second; } res.push_back(Interval(start,end)); index++; } return res; } };
本地测试正确,不知道哪里有问题
#include"stdafx.h" #include<iostream> #include<vector> #include<set> #include<math.h> #include<map> #include<sstream> #include<algorithm> #include<stack> #include<queue> using namespace std; struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; class Solution { public: vector<Interval> merge(vector<Interval>& intervals) { auto next = intervals.begin(); auto pre = next++; while (next != intervals.end()) { if (pre->end >= next->start) { pre->end = next->end; next = intervals.erase(next); } else { pre++; next++; } } return intervals; } }; int main() { vector<Interval> coll; Interval a = Interval(1, 3); Interval b = Interval(2, 6); Interval c = Interval(8, 10); Interval d = Interval(15, 18); coll.push_back(a); coll.push_back(b); coll.push_back(c); coll.push_back(d); // coll.erase(coll.begin()); Solution s; s.merge(coll); for (auto i : coll) cout << i.start << " " << i.end << endl; system("pause"); return 0; }