Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note that intervals which only touch at a point are non-overlapping. For example, [1, 2] and [2, 3] are non-overlapping.
We can sort the intervals based on their starting times. Track prevEnd from the previous interval. When comparing two intervals, consider the smaller end value to minimize overlaps with subsequent intervals.
Actually, the problem is similar to classic greedy problem - Interval Scheduling Problem where we are given a collection of intervals, find the maximum number of intervals that are non-overlapping".
publicclassSolution {
publicinteraseOverlapIntervals(int[][] intervals) {
if (intervals.length== 0) {
return 0;
}
// Sort intervals by their end times Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int end = intervals[0][1];
int count = 1;
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0]>= end) {
end = intervals[i][1];
count++;
}
}
return intervals.length- count;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
deferaseOverlapIntervals(self, intervals: List[List[int]]) -> int:
ifnot intervals:
return0# Sort intervals by their end times intervals.sort(key=lambda x: x[1])
end = intervals[0][1]
count =1for i in range(1, len(intervals)):
if intervals[i][0] >= end:
end = intervals[i][1]
count +=1return len(intervals) - count