Skip to content

Commit 4aa39ad

Browse files
committed
added remove covered intervals
1 parent a707039 commit 4aa39ad

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

october/removeCoveredIntervals.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
3+
Given a list of intervals, remove all intervals that are covered by another interval in the list.
4+
5+
Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.
6+
7+
After doing so, return the number of remaining intervals.
8+
9+
10+
Input: intervals = [[1,4],[3,6],[2,8]]
11+
Output: 2
12+
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
13+
14+
*/
15+
16+
//solution
17+
18+
using interval = vector<int>;
19+
20+
bool comparator(interval a, interval b)
21+
{
22+
if(a[0] == b[0]){
23+
return a[1] > b[1];
24+
}
25+
return a[0] < b[0];
26+
}
27+
28+
class Solution {
29+
public:
30+
int removeCoveredIntervals(vector<vector<int>>& intervals) {
31+
//sort based on starting interval
32+
33+
sort(intervals.begin(),intervals.end(),comparator);
34+
int ans=intervals.size();
35+
int maxEnd = 0;
36+
for(interval cur:intervals)
37+
{
38+
int curEnd = cur[1];
39+
if(curEnd <= maxEnd){
40+
ans--;
41+
}
42+
43+
maxEnd = max(maxEnd, curEnd);
44+
}
45+
return ans;
46+
}
47+
};

0 commit comments

Comments
 (0)