1. Topic
Give you a list of intervals, please delete the intervals covered by other intervals in the list.
Only when c <= a and b <= d, we consider the interval [a, b) to be covered by the interval [c, d).
After completing all the deletion operations, please return the number of remaining intervals in the list.
Example:
Input: intervals = [[1,4],[3,6],[2,8]] Output: 2 Explanation: The interval [3,6] is
covered by the interval [2,8] , so it is deleted .
Two: code
Ideas:
- This question can use the greedy algorithm, first sort (ascending start time sort), and sort the intervals with the same start time end time in descending order
- After sorting, traverse each interval, if end>prev_end, it means that the interval is not covered by the previous interval, cnt++
class Solution {
private:
static bool cmp(const vector<int> &a,const vector<int> &b){
if(a[0]==b[0]){
return a[1]>=b[1];
}else return a[0]<b[0];
}
public:
int removeCoveredIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(),intervals.end(),cmp);
int prev_end=0,end=0,cnt=0;
for(auto i:intervals){
end=i[1];
// cout<<i[0]<<'\t'<<i[1]<<endl;
if(end>prev_end){
cnt++;
prev_end=end;
}
}
return cnt;
}
};
note:
- When using the sort() function, the third parameter is a comparison function, which must be a static member function (the member function in the class will add a parameter this by default, and static will not be added), or a non-class member Function, or lambda function
- The writing of lambda function:
sort(intervals.begin(),intervals.end(),[](const vector<int> &a,const vector<int> &b){
return a[0]==b[0]?a[1]>=b[1]:a[0]<b[0];
});
- The parameters of the comparison function: const & should be written, otherwise, if you write a general type, it will cause a lot of meaningless copies, resulting in an increase in time.