今天的三道题目,都算是 重叠区间 问题,大家可以好好感受一下。 都属于那种看起来好复杂,但一看贪心解法,惊呼:这么巧妙!
这种题还是属于那种,做过了也就会了,没做过就很难想出来。
不过大家把如下三题做了之后, 重叠区间 基本上差不多了
452. 用最少数量的箭引爆气球
class Solution {
public int findMinArrowShots(int[][] points) {
Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));
int count = 1;
for (int i = 1; i < points.length; i++) {
if (points[i][0] > points[i - 1][1]) {
count++;
} else {
points[i][1] = Math.min(points[i][1], points[i - 1][1]);
}
}
return count;
}
}
435. 无重叠区间
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
int uniqueCount = 1;
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] < intervals[i - 1][1]) {
intervals[i][1] = Math.min(intervals[i - 1][1], intervals[i][1]);
} else {
uniqueCount++;
}
}
return intervals.length - uniqueCount;
}
}
763.划分字母区间
class Solution {
public List<Integer> partitionLabels(String S) {
List<Integer> result = new ArrayList<>();
int[] lastOccurrence = new int[26];
char[] characters = S.toCharArray();
for (int i = 0; i < characters.length; i++) {
lastOccurrence[characters[i] - 'a'] = i;
}
int startIdx = 0;
int endIdx = -1;
for (int i = 0; i < characters.length; i++) {
startIdx = Math.max(startIdx, lastOccurrence[characters[i] - 'a']);
if (i == startIdx) {
result.add(startIdx - endIdx);
endIdx = startIdx;
}
}
return result;
}
}