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;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值