xinyu04

导航

LeetCode 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] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. 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 xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. 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.

Solution

只需要先将坐标排序,然后维护一个共同覆盖的区间即可。

点击查看代码
class Solution {
public:
    int findMinArrowShots(vector<vector<int>>& points) {
        sort(points.begin(), points.end());
        int n = points.size();
        int ans=0;
        if(n==1)return 1;
        
        int st=points[0][0], ed = points[0][1];
        ans++;
        for(int i=1;i<n;i++){
            if(points[i][0]>ed){
                st=points[i][0];ed = points[i][1];
                ans++;
            }
            else{
                st = max(st, points[i][0]);
                ed = min(ed, points[i][1]);
            }
        }
        return ans;
    }
};

posted on 2022-09-15 20:40  Blackzxy  阅读(20)  评论(0编辑  收藏  举报