Erase Overlapping Intervals Algorithm in C++ and Dart
Erase Overlapping Intervals Algorithm in C++ and Dart
This code implements a solution for the 'Erase Overlapping Intervals' problem, a classic example of interval scheduling, using a greedy approach. The goal is to find the minimum number of intervals to remove so that no overlaps remain in the given set of intervals.
C++ Implementation
class Solution {
public:
static bool cmp(const vector<int>& a, const vector<int>& b) {
return a[0] < b[0];
}
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
int result = 1;
sort(intervals.begin(),intervals.end(),cmp);
for(int i = 1; i < intervals.size(); i++) {
if(intervals[i][0] >= intervals[i-1][1])
result++;
else
intervals[i][1] = min(intervals[i][1],intervals[i-1][1]);
}
return intervals.size() - result;
}
};
Dart Implementation
class Solution {
bool cmp(List<int> a, List<int> b) {
return a[0] < b[0];
}
int eraseOverlapIntervals(List<List<int>> intervals) {
int result = 1;
intervals.sort(cmp);
for(int i = 1; i < intervals.length; i++) {
if(intervals[i][0] >= intervals[i-1][1])
result++;
else
intervals[i][1] = min(intervals[i][1],intervals[i-1][1]);
}
return intervals.length - result;
}
}
Explanation:
- Sorting: The intervals are sorted by their start times to ensure a greedy selection strategy. The
cmpfunction handles the sorting comparison in both languages. - Iteration: The code iterates through the sorted intervals, comparing each interval's start time with the previous interval's end time.
- Overlapping Check: If the current interval's start time is greater than or equal to the previous interval's end time, they don't overlap, and the
resultis incremented to count this non-overlapping interval. Otherwise, the current interval's end time is minimized to avoid further overlaps. - Result Calculation: Finally, the number of intervals to remove is calculated by subtracting the
result(number of non-overlapping intervals) from the total number of intervals.
Key Points:
- This algorithm provides an efficient and optimal solution to the 'Erase Overlapping Intervals' problem.
- The greedy approach focuses on selecting intervals that maximize the number of non-overlapping intervals, leading to the minimum number of removals.
- The code is presented in both C++ and Dart, demonstrating the algorithm's adaptability across languages.
原文地址: https://www.cveoy.top/t/topic/qhug 著作权归作者所有。请勿转载和采集!