435. Non-overlapping Intervals

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.

首先对intervals按照后一项的大小进行排序。(直接将两数字相减作为比较值比Integer.compare方法更快。)
贪心算法,将已取得的最大值max设置为最小整数值。
遍历intervals,如果当前interval的左侧小于max,则不能选择该interval,计数加一。
反之则可以选择interval,更新max的值为interval的最大值。
返回总数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a,b) -> a[1] - b[1]);
int max = Integer.MIN_VALUE;
int count = 0;
for(int[] interval : intervals){
if(interval[0] < max){
count++;
}
else{
max = interval[1];
}
}
return count;
}
}
Author

Xander

Posted on

2022-04-19

Updated on

2022-04-19

Licensed under

Comments