目录
LeetCode 435.无重叠空间
文章讲解:代码随想录
视频讲解:贪心算法,依然是判断重叠区间 | LeetCode:435.无重叠区间_哔哩哔哩_bilibili
力扣题目:LeetCode 435.无重叠空间
代码如下(Java):
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals,(a,b)->{
return Integer.compare(a[0],b[0]);
});
int count = 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]);
continue;
}else{
count++;
}
}
return intervals.length - count;
}
}
LeetCode 763.划分字母区间
文章讲解:代码随想录
视频讲解:贪心算法,寻找最远的出现位置! LeetCode:763.划分字母区间_哔哩哔哩_bilibili
力扣题目:LeetCode 763.划分字母区间
代码如下(Java):
class Solution {
public List<Integer> partitionLabels(String s) {
List<Integer> list = new LinkedList<>();
int[] edge = new int[26];
char[] chars = s.toCharArray();
//记录字符串中每个字符的最远位置
for(int i = 0; i < chars.length; i++){
edge[chars[i] - 'a'] = i;
}
int idx = 0;
int last = -1;
for(int i = 0; i < chars.length; i++){
//更新片段中的最远位置
idx = Math.max(idx, edge[chars[i] - 'a']);
if(i == idx){
list.add(i - last);
last = i;
}
}
return list;
}
}
LeetCode 56.合并区间
文章讲解:代码随想录
视频讲解:贪心算法,合并区间有细节!LeetCode:56.合并区间_哔哩哔哩_bilibili
力扣题目:LeetCode 56.合并区间
代码如下(Java):
class Solution {
public int[][] merge(int[][] intervals) {
List<int[]> res = new LinkedList<>();
Arrays.sort(intervals, (x, y)-> Integer.compare(x[0], y[0]));
int start = intervals[0][0];
int rightmostRightBound = intervals[0][1];
for(int i = 1; i < intervals.length; i++){
if(intervals[i][0] > rightmostRightBound){
res.add(new int[]{start, rightmostRightBound});
start = intervals[i][0];
rightmostRightBound = intervals[i][1];
}else{
rightmostRightBound = Math.max(rightmostRightBound, intervals[i][1]);
}
}
res.add(new int[]{start, rightmostRightBound});
return res.toArray(new int[res.size()][]);
}
}