[LeetCode] Remove Covered Intervals

1288. Remove Covered Intervals

Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.

The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.

Return the number of remaining intervals.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int removeCoveredIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](vector<int>& v1, vector<int>& v2){
if(v1[0] == v2[0]) return v1[1] > v2[1];
return v1[0] < v2[0];
});
int ma = intervals[0][1], res = 0;

for(int i = 1; i < intervals.size(); i++) {
if(ma >= intervals[i][1]) res++;
else ma = intervals[i][1];
}

return intervals.size() - res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/20/PS/LeetCode/remove-covered-intervals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.