✅DAY30 贪心算法 | 452. 用最少数量的箭引爆气球 | 435. 无重叠区间 | 763.划分字母区间

452. 用最少数量的箭引爆气球

解题思路:首先把原数组按左边界进行排序。然后比较[i-1]的右边界和[i]的左边界是否重叠,如果重叠,更新当前右边界为最小右边界和[i+1]的左边界判断是重叠。

python 复制代码
class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        if len(points) == 0: return 0
        points.sort(key=lambda x: x[0])
        result = 1
        for i in range(1, len(points)):
            if points[i][0] > points[i-1][1]: # 第二段的头和第一段的尾不衔接
                result += 1
            else:
                points[i][1] = min(points[i-1][1], points[i][1]) 
                # else是这两段重叠,但是要判断下一个部分是否重叠
                # 更新尾为最小的右边界,如果下一个[i][0]< [i-1][1],则又有一段重叠
        return result

优化:按右边界排序的方式通常更直观,因为只需要维护一个变量 current_end 表示当前的射击位置,不需要更新区间边界,也减少了不必要的操作。

python 复制代码
class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        if not points: return 0
        points.sort(key=lambda x: x[1])  # 按右边界排序
        result = 1
        current_end = points[0][1]
        for i in range(1, len(points)):
            if points[i][0] > current_end:
                result += 1
                current_end = points[i][1]
        return result

435. 无重叠区间

python 复制代码
class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        if not intervals: return 0

        intervals.sort(key = lambda x:x[0])
        count = 0

        for i in range(1, len(intervals)):
            if intervals[i-1][1] > intervals[i][0]: # 存在重叠
                intervals[i][1] = min(intervals[i-1][1], intervals[i][1])
                count += 1
        return count

763. 划分字母区间

python 复制代码
class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        last_occ = {}
        result = []
        for i, char in enumerate(s):
            last_occ[char] = i
        start_index, end_index = 0, 0
        for i, char in enumerate(s):
            end_index = max(end_index, last_occ[char])#找出当前字符出现的最远位置
            if i == end_index:#i遍历到当前end的最尾部,说明前面的所有出现字符到这停下了
                result.append(end_index - start_index + 1)
                start_index = i + 1
        return result
相关推荐
法拉第第21 小时前
淘汰策略之tinyLFU
算法
mit6.82421 小时前
[Tongyi] 工具集成 | run_react_infer
人工智能·深度学习·算法
闻缺陷则喜何志丹21 小时前
【C++贪心】P8769 [蓝桥杯 2021 国 C] 巧克力|普及+
c++·算法·蓝桥杯·洛谷
2501_918126911 天前
使用HTML和Python开发街霸游戏
python·游戏·html
杨小码不BUG1 天前
灯海寻踪:开灯问题的C++精妙解法(洛谷P1161)
c++·算法·数学建模·位运算·浮点数·信奥赛·csp-j/s
杨小码不BUG1 天前
心痛之窗:滑动窗口算法解爱与愁的心痛(洛谷P1614)
开发语言·c++·算法·滑动窗口·csp-j/s·多维向量
咖啡啡不加糖1 天前
贪心算法详解与应用
java·后端·算法·贪心算法
無斜1 天前
【LabVIEW实用开发】--- LabVIEW调用python脚本
开发语言·python·labview
一只鱼^_1 天前
力扣第470场周赛
数据结构·c++·算法·leetcode·深度优先·动态规划·启发式算法
数据牧羊人的成长笔记1 天前
python爬虫scrapy框架使用
爬虫·python·scrapy