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

文章目录

  • 一、题目
  • 二、解法
  • 三、完整代码

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

一、题目

【算法与数据结构】452、LeetCode用最少数量的箭引爆气球_第1张图片

二、解法

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

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 
# include 
# include 
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

你可能感兴趣的:(算法,算法)