算法Week11.01 - LeetCode 452. Minimum Number of Arrows to Burst Balloons
来源:互联网 发布:fft算法原理 编辑:程序博客网 时间:2024/06/04 01:17
题目大意
使用尽可能少的箭清理所有气球。
解题思路
先说一下解题方法,再来说明这种方法的合理性。
维护一个变量 arrow
,arrow
指示当前已清理的范围([+∞, arrow]),如果一个气球的范围与清理范围有重叠,则说明该气球已经被清理;
对所有气球按照左值进行排序,得到左值非递增的序列;
遍历序列,如果气球已被清理,则跳过;如果气球未被清理,则朝其左值的位置射一箭(更新 arrow
的值);直到所有气球被清理。
要说明解题的合理性,主要是说明贪心步的正确性,这里的贪心步是指“朝其左值的位置射一箭”。
以题目给出的示例说明,让我们先来看第一步,很显然进行第一步时该气球没有被清理,于是必须在 [10, 16] 之间射一箭;清理第一步的气球,理论上在 [10, 16] 的任意位置射一箭都是可以的,不过我们总是贪心地希望清理范围越大越好;并且第一步清理的气球具有的左值是最大的,那么选择 10 一定不会错过其他气球(否则该气球必定具有更大的左值);因此选择 10 作为射箭位置一定不会错过最优解。
更新 arrow
的值为10,继续遍历序列,直到第一个未被清理的气球,此时问题重新转化为与上相似的问题;这样将序列遍历完便可保证得到最优解,时间复杂度取决于排序,为 O(nlogn)。
源代码
#include <vector>#include <algorithm>using namespace std;class Comp {public: bool operator()(const pair<int, int>& a, const pair<int, int>& b) { return a.first >= b.first; }};class Solution {public: int findMinArrowShots(vector<pair<int, int>>& points) { if (points.empty()) return 0; sort(points.begin(), points.end(), Comp()); int arrow = points[0].first; int cnt = 1; for (int i = 1; i < points.size(); i++) { if (points[i].second >= arrow) continue; else { arrow = points[i].first; cnt++; } } return cnt; }};
0 0
- 算法Week11.01 - LeetCode 452. Minimum Number of Arrows to Burst Balloons
- LeetCode 452. Minimum Number of Arrows to Burst Balloons
- 【leetcode】452. Minimum Number of Arrows to Burst Balloons【M】
- LeetCode 452. Minimum Number of Arrows to Burst Balloons
- Leetcode 452. Minimum Number of Arrows to Burst Balloons[medium]
- [leetcode] 452. Minimum Number of Arrows to Burst Balloons
- Leetcode-452. Minimum Number of Arrows to Burst Balloons
- 【LeetCode】 452. Minimum Number of Arrows to Burst Balloons
- [Leetcode] 452. Minimum Number of Arrows to Burst Balloons
- [leetcode]452. Minimum Number of Arrows to Burst Balloons
- [LeetCode]452. Minimum Number of Arrows to Burst Balloons
- LeetCode 452. Minimum Number of Arrows to Burst Balloons
- LeetCode 452. Minimum Number of Arrows to Burst Balloons
- LeetCode 452. Minimum Number of Arrows to Burst Balloons
- 452. Minimum Number of Arrows to Burst Balloons| Leetcode Greedy
- 【LeetCode】452. Minimum Number of Arrows to Burst Balloons
- LeetCode 452. Minimum Number of Arrows to Burst Balloons
- leetcode 452. Minimum Number of Arrows to Burst Balloons
- <head> 标签使用
- 经典排序算法总结--冒泡、快排、插入、希尔、归并、选择
- SecureCRT无法连接Linux虚拟机,返回账号密码错误Password Authentication Failed
- 再入凡尘
- springmvc使用@requestBody注释json数据,浏览器错误415
- 算法Week11.01 - LeetCode 452. Minimum Number of Arrows to Burst Balloons
- Android学习 (三) 在活动之间穿梭之Intent
- 如何用消息系统避免分布式事务
- 经典排序算法:希尔排序(Shell Sort)
- 阻塞队列(CountDownLatch代替notify+wait解决wait释放锁,notify不释放锁问题)
- 19、Spring MVC 之 Container Config
- asdf
- 玩转Java对象和XML相互转换
- TCP--传输控制协议