Minimum Number of Arrows to Burst Balloons_Week8

Minimum Number of Arrows to Burst Balloons_Week8

题目:(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.

难度: Medium

解题思路:
题目意为,一个方盘上摆着直径不同的气球,题目给出所有气球的横坐标范围(绝对值即直径),不给纵坐标因为不重要。一支飞镖竖着射过去,不停止地直到射穿该y轴上所有气球,问射完所有气球最少需要多少飞镖。
解决思路:
先将所有气球排序,用自定义的mySort来排序:将所有气球按气球的end(即直径的最后)排序,若end相等,则按照start(直径的开始)排序。
第一支飞镖射第一个气球的end,用arrowCoordinate记录上一支飞镖射的位置,遍历所有气球,若该气球是落在上一支飞镖的射程范围内,则不需要添加飞镖;否则多射击一支飞镖

#include <iostream>
using namespace std;

class Solution {
public:
    int findMinArrowShots(vector<pair<int, int>>& points) {
        int arrowNum = 0;//记录最少需要的arrow数量 
        int arrowCoordinate  = INT_MIN; //最后一次shot的坐标(取可射击范围内最大值) 

        //将气球在x坐标轴上分段排序
        sort(points.begin(), points.end(), mySort);

        int size = points.size();
        for (int i = 0; i < size; i++) {
            //若本气球在最后shot的arrow范围内,则跳过 
            if (arrowCoordinate != INT_MIN && points[i].first <= arrowCoordinate) {
                continue;
            }
            //否则说明不在射击范围内,需要再shot一个arrow 
            arrowCoordinate = points[i].second;
            arrowNum++; 
        }
        return arrowNum; 
    }

    //排序,将两个点的终点相比较,若终点相同,则比较起点 
    static bool mySort(pair<int, int>& a, pair<int, int>& b) {
        if (a.second == b.second) {
            return a.first < b.first;
        } else {
            return a.second < b.second;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/m0_38072045/article/details/78385176