452. 用最少数量的箭引爆气球, 435. 无重叠区间, 763.划分字母区间

思路

按照左端升序排序

如果这个气球的start>end:说明可以和当前气球组一起引爆,加入气球组

否则:当前气球组是最佳配置,添加一个新的气球组,更新end区间

代码

class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        if not points:
            return 0
        points.sort(key=lambda x:x[0])
        count=1 
        start,end=points[0]
        for point in points:
            if point[0]>end:
                count+=1
                start,end=point 
            else:
                start=point[0]
                end=min(end,point[1])
        return count 

 思路

影响的只有end,思考不同情况下对于end的处理

代码

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        intervals.sort(key=lambda x:x[1])
        end=intervals[0][1]
        count=0
        for interval in intervals[1:]:
            if interval[0]>=end:
                end=interval[1]
            else:
                count+=1
        return count

思路

要找到最短的分段,至少要达到当前字母最后一个位置

在遍历当前位置时,不断收集新的字母,每个新的字母都有最后一个位置,因此至少要遍历到字母集中最大的最后位置。当index=end时完成最短的分段

代码

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        last_occurrence={char:index for index,char in enumerate(s)}
        start=0
        end=0
        partitions=[]
        for index,char in enumerate(s):
            end=max(end,last_occurrence[char])
            if index==end:
                partitions.append(end-start+1)
                start=end+1
        return partitions

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值