LeetCode452. Minimum Number of Arrows to Burst Balloons

文章目录

一、题目

There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where pointsi = xstart, xend denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.

Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.

Given the array points, return the minimum number of arrows that must be shot to burst all balloons.

Example 1:

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

Output: 2

Explanation: The balloons can be burst by 2 arrows:

  • Shoot an arrow at x = 6, bursting the balloons 2,8 and 1,6.
  • Shoot an arrow at x = 11, bursting the balloons 10,16 and 7,12.
    Example 2:

Input: points = \[1,2,3,4,5,6,7,8]

Output: 4

Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.

Example 3:

Input: points = \[1,2,2,3,3,4,4,5]

Output: 2

Explanation: The balloons can be burst by 2 arrows:

  • Shoot an arrow at x = 2, bursting the balloons 1,2 and 2,3.
  • Shoot an arrow at x = 4, bursting the balloons 3,4 and 4,5.

Constraints:

1 <= points.length <= 105

pointsi.length == 2

-231 <= xstart < xend <= 231 - 1

二、题解

cpp 复制代码
class Solution {
public:
    static bool cmp(vector<int>& a,vector<int>& b){
        return a[0] < b[0];
    }
    int findMinArrowShots(vector<vector<int>>& points) {
        int n = points.size();
        //按左边界从小到大排序
        sort(points.begin(),points.end(),cmp);
        int res = 1;
        for(int i = 1;i < n;i++){
            //如果当前气球左边界大于上一个气球的右边界
            if(points[i][0] > points[i-1][1]) res++;
            //如果重合,则更新右端点值
            else points[i][1] = min(points[i][1],points[i-1][1]);
        }
        return res;
    }
};
相关推荐
程序员清风6 分钟前
排序算法:从冒泡排序到归并排序
数据结构·算法·排序算法
万年咸鱼6 分钟前
C语言内功心法篇——变量与数据类型
c语言·jvm·算法
张小凡vip23 分钟前
Kubernetes--k8s---了解和使用 ServiceAccount
容器·贪心算法·kubernetes
蒸蒸yyyyzwd25 分钟前
后端学习笔记 day58
c++·八股
道尔柯南27 分钟前
【QT】从零认识 Qt:跨平台 C++ GUI 开发入门
开发语言·c++·qt
Omics Pro32 分钟前
反式感知虚拟细胞!超越线性序列
数据库·人工智能·算法·机器学习·自然语言处理
-dzk-36 分钟前
【动态规划】LC 152.乘积最大子数组
算法·动态规划
积流成海37 分钟前
一致性哈希原理与实现:分布式系统负载均衡
算法·负载均衡·哈希算法·哈希函数·盘子工具站
MayZork1 小时前
std::filesystem 文件操作详解
开发语言·c++·qt
Ada's10 小时前
【计算机基础系列】003:Python数据结构
开发语言·数据结构·python