452. Minimum Number of Arrows to Burst Balloons| Leetcode Greedy

来源:互联网 发布:苹果74g网络怎么设置 编辑:程序博客网 时间:2024/06/10 03:20

Description

There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it’s horizontal, y-coordinates don’t matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.

Difficulty: Medium

Thinking

题目要求,有一堆气球分布在X轴上,其直径用它在X轴的起点和终点表示,如果两气球直径区间有重叠,且有一支箭射在两气球重叠区间内,则两个气球都会被扎破。多个同理。求最少能用多少支箭将所有气球扎破。
因此我先将这组气球按直径起点先排序。然后从第一个气球算起,将能重叠射破的气球计为一堆,重叠的判断条件为后面气球的start坐标是否比这堆第一个气球的end坐标小。
一开始用冒泡算法进行排序,Time Limit Exceeded了。
直接用sort快排后不超时了,但结果错误。
错误在于用start坐标对气球进行排序,可能出现分堆错误的情况。于是改成按照气球直径的end坐标排序,结果正确。

Solution

class Solution {public:    static bool compare(pair<int, int>&a, pair<int, int>& b){        if(a.second < b.second) return true;        else if(a.second == b.second) return a.first < b.first;        else return false;    }     int findMinArrowShots(vector<pair<int, int>>& points) {        int size = points.size();        if(size == 0) return 0;        sort(points.begin(), points.end(), compare);        int arrow = 1;        int pto = points[0].second;        for(int i = 1; i < size; i++){            if(points[i].first <= pto){                continue;            }            else{                pto = points[i].second;                arrow++;            }        }        return arrow;    }};
0 0
原创粉丝点击