LeetCode 题解工作台

用最少数量的箭引爆气球

有一些球形气球贴在一堵用 XY 平面表示的墙面上。墙面上的气球记录在整数数组 points ,其中 points[i] = [x start , x end ] 表示水平直径在 x start 和 x end 之间的气球。你不知道气球的确切 y 坐标。 一支弓箭可以沿着 x 轴从不同点 完全垂直 地…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们可以将所有气球按照右端点升序排序,然后从左到右遍历气球,维护当前的箭所能覆盖的最右端点 ,如果当前气球的左端点 大于 ,说明当前箭无法覆盖当前气球,需要额外射出一支箭,那么答案加一,同时更新 为当前气球的右端点 。 遍历结束后,即可得到答案。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有一些球形气球贴在一堵用 XY 平面表示的墙面上。墙面上的气球记录在整数数组 points ,其中points[i] = [xstart, xend] 表示水平直径在 xstart 和 xend之间的气球。你不知道气球的确切 y 坐标。

一支弓箭可以沿着 x 轴从不同点 完全垂直 地射出。在坐标 x 处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstartxend 且满足  xstart ≤ x ≤ xend则该气球会被 引爆 可以射出的弓箭的数量 没有限制 。 弓箭一旦被射出之后,可以无限地前进。

给你一个数组 points返回引爆所有气球所必须射出的 最小 弓箭数 

 

示例 1:

输入:points = [[10,16],[2,8],[1,6],[7,12]]
输出:2
解释:气球可以用2支箭来爆破:
-在x = 6处射出箭,击破气球[2,8]和[1,6]。
-在x = 11处发射箭,击破气球[10,16]和[7,12]。

示例 2:

输入:points = [[1,2],[3,4],[5,6],[7,8]]
输出:4
解释:每个气球需要射出一支箭,总共需要4支箭。

示例 3:

输入:points = [[1,2],[2,3],[3,4],[4,5]]
输出:2
解释:气球可以用2支箭来爆破:
- 在x = 2处发射箭,击破气球[1,2]和[2,3]。
- 在x = 4处射出箭,击破气球[3,4]和[4,5]。

 

提示:

  • 1 <= points.length <= 105
  • points[i].length == 2
  • -231 <= xstart < xend <= 231 - 1
lightbulb

解题思路

方法一:排序 + 贪心

我们可以将所有气球按照右端点升序排序,然后从左到右遍历气球,维护当前的箭所能覆盖的最右端点 lastlast,如果当前气球的左端点 aa 大于 lastlast,说明当前箭无法覆盖当前气球,需要额外射出一支箭,那么答案加一,同时更新 lastlast 为当前气球的右端点 bb

遍历结束后,即可得到答案。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 为气球的数量。

相似题目:

1
2
3
4
5
6
7
8
9
class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        ans, last = 0, -inf
        for a, b in sorted(points, key=lambda x: x[1]):
            if a > last:
                ans += 1
                last = b
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate demonstrates understanding of greedy algorithms.

  • question_mark

    Candidate can efficiently implement sorting and iteration techniques.

  • question_mark

    Candidate recognizes the importance of minimizing overlap to reduce arrow count.

warning

常见陷阱

外企场景
  • error

    Not sorting the balloons by their end positions, which leads to suboptimal arrow placement.

  • error

    Overcomplicating the problem by considering unnecessary factors like y-coordinates or specific positions within the balloon's range.

  • error

    Failing to account for all balloons in one pass, resulting in unnecessary arrows.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to account for balloons with varying sizes.

  • arrow_right_alt

    Extend the problem to consider balloons represented in 3D space, introducing more complex geometry.

  • arrow_right_alt

    Change the arrows' movement to diagonals or allow for multi-directional shots.

help

常见问题

外企场景

用最少数量的箭引爆气球题解:贪心·invariant | LeetCode #452 中等