1. 程式人生 > >Greedy--Minimum Number of Arrows to Burst Balloons (Medium)

Greedy--Minimum Number of Arrows to Burst Balloons (Medium)

原題

  • Problem 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.

  • Sample Input

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

  • Sample Output

    2

解題思路:

題目大概意思就是:
給定了每一個氣球的區間(起始點和終止點),判斷需要多少弓箭手才能射爆所有的氣球(一支箭可以射穿多個氣球)

貪心:

此題貪心在於->>對所有的氣球的區間進行排序,然後每發射一個弓箭,便搜尋所有能夠被射中的氣球,一個不落。

程式碼思路:

1、對所有氣球的區間通過上界進行排序。
2、以第一個氣球的區間為第一把弓箭的射擊範圍區間,之後逐個判斷後面的氣球的區間

是否和弓箭的射擊區間有交集,若有交集則弓箭也可射中此氣球並更新弓箭的射擊區間,直至有氣球無法被此弓箭射中。
3、再一次增加一個弓箭,以上一個無法被射中的氣球的區間為此弓箭的射擊範圍區間。

程式碼:

#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    int findMinArrowShots(vector<pair<int, int>>& points) {
        if (points.size() == 0
) return 0; sort(points.begin(), points.end(), cmp);//begin()和end()返回的是迭代器 int shootNum = 1;//初始化弓箭手的數量為1 int shootBegin = points[0].first;//初始化弓箭手的射擊區域 int shootEnd = points[0].second; for (int i = 1; i < points.size(); i++) { if (points[i].first <= shootEnd)//此氣球在弓箭射擊範圍內 { shootBegin = points[i].first; if (points[i].second <= shootEnd) { shootEnd = points[i].second; } }else//無法射中此氣球->增加一個弓箭,更新弓箭區間 { shootNum++; shootBegin = points[i].first; shootEnd = points[i].second; } } return shootNum; } static bool cmp(const pair<int,int>&a,const pair<int,int>&b) { return a.first < b.first; } };