LeetCode·452.用最少的数目的箭引爆气球·贪心
LeetCode 贪心 最少 数目 引爆 气球
2023-09-27 14:26:29 时间
链接:https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/solution/chun-c-by-xun-ge-v-9klf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目
示例
思路
解题思路
本题与757题思路基本一样
链接:https://leetcode.cn/problems/set-intersection-size-at-least-two/solution/chun-c-by-xun-ge-v-t4m9/
来源:力扣(LeetCode)
贪心
题目要求使用最少的箭射最多的气球,所有每次都应该使箭射的气球数最大。
我们将气球集合[1]升序,当[1]相同时,将[0]降序,这里降序的目的是,使得我们小集合在前面,大集合在后面,我们先处理小集合,那么大集合就可以不需要处理,因为当左边界相同时,当小集合能满足其中两个元素相同,那么大集合肯定与能满足,因为小集合整个都可以装入大集合中。
具体实现
定义一个变量max为箭,每次箭值我们都取气球边界最大,使箭能射更多气球,遍历整个集合,因为集合已经升序处理,所有射箭时存在两张情况
- 当左边界比max小时,说明此箭可以射点这个气球
- 当左边界比max大时,说明此箭射不了这个气球,因为集合已经升序,当前气球射不了,那么之后的气球也无能为力,换更大的箭,换当前气球最大边界
代码
int cmp(void* _a, void* _b) {//排序
int *a = *(int**)_a, *b = *(int**)_b;
return a[1] < b[1] ? -1 : 1;
}
int findMinArrowShots(int** points, int pointsSize, int* pointsColSize){
if(pointsSize == 0)
{
return 0;
}
qsort(points, pointsSize, sizeof(int*), cmp);//排序
int conut = 1;//初始化箭数
int max = points[0][1];//初始化箭值
for(int i = 1; i < pointsSize; i++)
{
if(max >= points[i][0])//当前气球能射
{
continue;
}
conut++;//射不到了,换箭
max = points[i][1];//更新箭值
}
return conut;
}
作者:xun-ge-v
链接:https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/solution/chun-c-by-xun-ge-v-9klf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时间空间复杂度
相关文章
- Leetcode: Nested List Weight Sum
- Leetcode: Search a 2D Matrix II
- [LeetCode]709. 转换成小写字母
- 139、【贪心算法】leetcode ——435. 无重叠区间(更新区间+记录不重叠区间)(C++版本)
- 131、【贪心算法】leetcode ——55. 跳跃游戏(贪心策略)(C++版本)
- 129、【动态规划/贪心算法】leetcode ——53. 最大子数组和(C++版本)
- 128、【贪心算法】leetcode ——376. 摆动序列(C++版本)
- 【算法/贪心】leetcode刷题路线(持续更新)
- 【LeetCode】172. Factorial Trailing Zeroes
- 【LeetCode】88. Merge Sorted Array (2 solutions)
- [LeetCode] 1080. Insufficient Nodes in Root to Leaf Paths 根到叶路径上的不足节点
- [LeetCode] 730. Count Different Palindromic Subsequences 计数不同的回文子序列的个数
- [LeetCode] 713. Subarray Product Less Than K 子数组乘积小于K
- [LeetCode] Exclusive Time of Functions 函数的独家时间
- [LeetCode] 279. Perfect Squares 完全平方数
- leetcode 240. Search a 2D Matrix II 搜索二维矩阵 II(中等)