LeetCode 452. Minimum Number of Arrows to Burst Balloons

来源:互联网 发布:java构造器有什么用 编辑:程序博客网 时间:2024/06/09 16:41

452. Minimum Number of Arrows to Burst Balloons

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.

Example:

Input:
[[10,16], [2,8], [1,6], [7,12]]

Output:
2

Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).

题目内容:
题目给出一个数组,其中数组的每个元素代表一个气球的起始位置xstart和终点位置xend。往一个点x射一支箭,可以刺破xstart<=x<=xend 的气球,题目要求我们求出最少射出多少支箭,可以刺穿所有的气球。

解题思路:
这一道题可以用贪心算法(Greedy Algorithms)来解决。首先对所有气球按照xend来进行升序排序。那么对于排序后的第一个气球,如果要刺穿他,必须有一支箭的位置在x0start<=x<=x0end,那么显然,如果我们选择的x越靠后,就越有可能把后面的气球也刺穿。所以,我选取x0end作为第一支箭的位置,再往后判断这支箭能否刺穿下一个气球,也就是判断下一个气球的xstart是否比x要小,是就可以刺穿,否则就要另外射多一支箭,以此类推,这样我们就可以保证每射一支箭都尽可能多的射穿气球。

代码:

////  main.cpp//  452. Minimum Number of Arrows to Burst Balloons////  Created by mingjc on 2017/4/16.//  Copyright © 2017年 mingjc. All rights reserved.//#include <iostream>#include <vector>#include <algorithm>using namespace std;class Solution {public:    int findMinArrowShots(vector<pair<int, int>>& points) {        if (points.empty()) return 0;        sort(points.begin(), points.end(), compare);        int currentArrowPos = points[0].second;        int arrowCnt = 1;        for (int i = 0; i < points.size(); i++) {            if (points[i].first <= currentArrowPos) {                continue;            }            arrowCnt++;            currentArrowPos = points[i].second;        }        return arrowCnt;    }    static bool compare(pair<int, int> p0, pair<int, int> p1) {        return p0.second < p1.second;    }};int main(int argc, const char * argv[]) {    // insert code here...    std::cout << "Hello, World!\n";    return 0;}
0 0