代码随想录训练营 贪心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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吃瓜太狼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值