Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 452. Minimum Number of Arrows to Burst Balloons

Rain Hu

452. Minimum Number of Arrows to Burst Balloons


一、題目

There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [x_start, x_end] denotes a balloon whose horizontal diameter stretches between x_start and x_end. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with x_start and x_end is burst by an arrow shot at x if x_start <= x <= x_end. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array points, return the minimum number of arrows that must be shot to burst all balloons.

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Greedy

int findMinArrowShots(vector<vector<int>>& points) {
    sort(points.begin(), points.end());
    int last = points[0][1];                // 右端點
    int cnt = 1;
    for (int i = 1; i < points.size(); i++) {
        if (points[i][0] <= last) {         // 只需比較右端點
            last = min(last, points[i][1]); // 重疊的範圍縮小,只需更新右端點
        } else {
            last = points[i][1];            // 若不重疊,則需再加另一隻箭,同時定義另一個重疊的區間
            cnt++;
        }
    }
    return cnt;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 149. Max Points on a Line
Next
[Algo] 1-9. Algorithm