代码随想录训练营 贪心05
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.
思路
看卡尔的图就搞懂了
代码
func eraseOverlapIntervals(intervals [][]int) int {
sort.Slice(intervals,func(i,j int)bool{return intervals[i][1] < intervals[j][1]})
res:=1
for i:=1;i<len(intervals);i++{
//排序后比较两个相邻数组的前一个尾巴 后一个头 ,小于则说明重合,然后记录两者较小的元素,作为重合元素的起始地方
if intervals[i][0]>= intervals[i-1][1]{//说明不重合
res++
}else{
intervals[i][1] = min(intervals[i-1][1],intervals[i][1])
}
}
return len(intervals)- res
}
func min(a,b int) int{
if a>b{return b}
return a
}
👻763. Partition Labels👻
You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
Return a list of integers representing the size of these parts.
思路
看注释
code
func max(a, b int) int {
if a < b {
a = b;
}
return a;
}
func partitionLabels(s string)[]int{
var res []int
var marks [26]int
size,left,right :=len(s),0,0
for i:=0;i<size;i++{ marks[s[i]-'a'] = i}//得到元素的最后一次出现的下标
for i:=0;i<size;i++{//
right =max(right ,marks[s[i]-'a'])
if i==right{//
res = append(res,right-left+1)
left = i+1
}
}
return res
}
👻763. Partition Labels👻
You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
Return a list of integers representing the size of these parts.
思路
和上题一样
code
func merge(intervals [][]int) [][]int {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0] < intervals[j][0]
})
res := make([][]int, 0, len(intervals))
left, right := intervals[0][0], intervals[0][1]
for i := 1; i < len(intervals); i++ {
if right < intervals[i][0] {//说明无交集
res = append(res, []int{left, right})
left, right = intervals[i][0], intervals[i][1]
} else {//找最长的加入
right = max(right, intervals[i][1])
}
}
res = append(res, []int{left, right}) // 将最后一个区间放入
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
博客围绕算法题展开,包含435. Non-overlapping Intervals和763. Partition Labels两道题。前者需计算移除最少区间使剩余区间不重叠的数量,后者要将字符串尽可能多地分割,使每个字母最多出现在一个部分,并返回各部分大小列表,还给出思路和代码。
798

被折叠的 条评论
为什么被折叠?



