Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Sorting
We can sort the intervals:
- by start time
- And then by length of interval (in case start times match)
So, now we pick up the interval which are longer; smaller intervals will be ignored or removed. Algo:
- Sort the array,
- and note the previous
left
andright
bound. - For evert interval
v
, ifv[0] > left && v[1] > right
, It’s a new uncovered interval,so we increment++res
.
Code
|
|