【算法与数据结构】452、LeetCode用最少数量的箭引爆气球

所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解

一、题目

在这里插入图片描述

二、解法

  思路分析:我们的目标是让一支弓箭尽可能多爆破气球,因此要找到重叠气球的区间数量,这样就可以抽象为一个排序+找交集的问题。排序我们用sort函数的重载,头文件是algorithm。然后遍历points数组,一个if判断两个气球是否挨着,如果不挨着则所需弓箭++。然后更新重叠气球的最小右边界,例如气球二的最小右边界更新为6,当i等于3时,nArrow++。
在这里插入图片描述
  程序如下

class Solution {
   
	static bool cmp(const vector<int>& a, const vector<int>& b) {
   
		if (a[0] == b[0]) return a[1] < b[1];
		return a[0] < b[0];
	}
public:
	int findMinArrowShots(vector<vector<int>>& points) {
   
		// 1.排序 2.找交集
		if (points.size()==0) return 0;
		int nArrow = 1;		// 箭数量,不为空至少要有一只箭
		sort(points.begin(), points.end(), cmp);
		for (int i = 1; i < points.size(); i++) {
   
			if (points[i][0] > points[i - 1][1]) nArrow++;	// 如果第i个气球和第i-1个气球不挨着,所需弓箭+1
			else points[i][1] = min(points[i - 1][1], points[i][1]); // 更新重叠气球最小右边界
		}
		return nArrow;
	}
};

复杂度分析:

  • 时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn),一个快速排序。
  • 空间复杂度: O ( 1 ) O(1) O(1),有一个快排,最差情况(倒序)时,需要n次递归调用。因此确实需要O(n)的栈空间
    可以看出代码并不复杂。

三、完整代码

# include <iostream>
# include <vector>
# include <algorithm>
using namespace std;

class Solution {
   
	static bool cmp(const vector<int>& a, const vector<int>& b) {
   
		if (a[0] == b[0]) return a[1] < b[1];
		return a[0] < b[0];
	}
public:
	int findMinArrowShots(vector<vector<int>>& points) {
   
		// 1.排序 2.找交集
		if (points.size()==0) return 0;
		int nArrow = 1;		// 箭数量,不为空至少要有一只箭
		sort(points.begin(), points.end(), cmp);
		for (int i = 1; i < points.size(); i++) {
   
			if (points[i][0] > points[i - 1][1]) nArrow++;	// 如果第i个气球和第i-1个气球不挨着,所需弓箭+1
			else points[i][1] = min(points[i - 1][1], points[i][1]); // 更新重叠气球最小右边界
		}
		return nArrow;
	}
};

int main() {
   
	vector<vector<int>> points = {
    {
   10, 16}, {
   2, 8},{
   1, 6},{
   7, 12} };
	Solution s1;
	int result = s1.findMinArrowShots(points);
	cout << "结果:" << result << endl;
	system("pause");
	return 0;
}

end

最近更新

  1. TCP协议是安全的吗?

    2023-12-29 14:04:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-29 14:04:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-29 14:04:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-29 14:04:04       18 阅读

热门阅读

  1. 出版实务 | 工具书

    2023-12-29 14:04:04       30 阅读
  2. C练习——一元二次方程求解

    2023-12-29 14:04:04       37 阅读
  3. 当 ML 遇到 DevOps:如何理解 MLOps

    2023-12-29 14:04:04       35 阅读
  4. js获取文件夹中的所有文件和子文件夹

    2023-12-29 14:04:04       29 阅读
  5. linux shell脚本分享!一个系统信息查询的工具箱

    2023-12-29 14:04:04       37 阅读
  6. C++基础普及:如何学好常用的数据结构

    2023-12-29 14:04:04       45 阅读
  7. (C)一些题19

    2023-12-29 14:04:04       27 阅读
  8. python字符串编码解码基础知识

    2023-12-29 14:04:04       36 阅读
  9. 矩阵的转置

    2023-12-29 14:04:04       28 阅读
  10. bash 变量作用域

    2023-12-29 14:04:04       31 阅读