代码:
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 5 using namespace std; 6 7 struct Interval { 8 int start; 9 int end; 10 Interval() : start(0), end(0) {} 11 Interval(int s, int e) : start(s), end(e) {} 12 }; 13 14 bool compare(Interval &a, Interval &b) 15 { 16 return a.start < b.start; 17 } 18 19 vector<Interval> merge(vector<Interval>& intervals) 20 { 21 vector<Interval> result; 22 sort(intervals.begin(), intervals.end(), compare); 23 for (int i = 0; i < intervals.size()-1; i++) 24 { 25 if ((i+1!=intervals.size()-1)&&intervals[i].end >= intervals[i + 1].start) 26 { 27 intervals[i].end = intervals[i + 1].end; 28 } 29 else 30 { 31 result.push_back(intervals[i]); 32 } 33 } 34 return result; 35 } 36 37 38 int main() 39 { 40 Interval I1(1,3); 41 Interval I2(2,6); 42 Interval I3(8, 10); 43 Interval I4(15,18); 44 vector<Interval> itervals; 45 itervals.push_back(I1); 46 itervals.push_back(I2); 47 itervals.push_back(I3); 48 itervals.push_back(I4); 49 50 vector<Interval> result = merge(itervals); 51 for (int i = 0; i < result.size(); i++) 52 { 53 cout << result[i].start << " " << result[i].end << endl; 54 } 55 }
时间: 2024-12-12 13:44:19