-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path1288. Remove Covered Intervals.cpp
80 lines (52 loc) · 1.61 KB
/
1288. Remove Covered Intervals.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
Given a list of intervals, remove all intervals that are covered by another interval in the list.
Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.
After doing so, return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Example 3:
Input: intervals = [[0,10],[5,12]]
Output: 2
Example 4:
Input: intervals = [[3,10],[4,10],[5,11]]
Output: 2
Example 5:
Input: intervals = [[1,2],[1,4],[3,4]]
Output: 1
Constraints:
1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= intervals[i][0] < intervals[i][1] <= 10^5
All the intervals are unique.
Show Hint #1
Hide Hint #2
Compare each interval to all others and check if it is covered by any interval.
class Solution {
public:
static bool comp(vector<int> a, vector<int> b){
if(a[0]==b[0])
return a[1]>b[1];
return a[0]<b[0];
}
int removeCoveredIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), comp);
int n=intervals.size();
int cnt=0;
int start=intervals[0][0], end=intervals[0][1];
for(int i=1;i<n;i++){
if(intervals[i][0]>=start && intervals[i][1]<=end){
cnt++;
start=min(start, intervals[i][0]);
end=max(end, intervals[i][1]);
} else {
start=intervals[i][0];
end=intervals[i][1];
}
}
return n-cnt;
}
};