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
}
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.
看注释
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
}
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.
和上题一样
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
}