【算法与数据结构】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

  • 19
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚安66

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值