编辑代码

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Interval {
    int start;
    int end;
};

bool compareIntervals(const Interval& a, const Interval& b) {
    return a.end < b.end;
}

vector<Interval> intervalCover(vector<Interval>& intervals) {
    vector<Interval> result;

    sort(intervals.begin(), intervals.end(), compareIntervals);

    int n = intervals.size();
    int i = 0;
    while (i < n) {
        int currentEnd = intervals[i].end;

        result.push_back(intervals[i]);

        while (i < n && intervals[i].start < currentEnd) {
            i++;
        }
    }

    return result;
}

int main() {
    Interval intervalArray[] = {
        {1, 5},
        {3, 4},
        {3, 5},
        {4, 8},
        {6, 8},
        {8, 9}
    };

    int arraySize = sizeof(intervalArray) / sizeof(intervalArray[0]);

    vector<Interval> intervals(intervalArray, intervalArray + arraySize);

    vector<Interval> result = intervalCover(intervals);

    cout << "选择的不相交区间:" << endl;
    for (vector<Interval>::const_iterator it = result.begin(); it != result.end(); ++it) {
        cout << "[" << it->start << ", " << it->end << "]" << endl;
    }

    return 0;
}