算法Week11.01 - LeetCode 452. Minimum Number of Arrows to Burst Balloons
2016-11-09 00:19
411 查看
题目大意
使用尽可能少的箭清理所有气球。解题思路
先说一下解题方法,再来说明这种方法的合理性。维护一个变量
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; } };
相关文章推荐
- LeetCode题解(Week 5) 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 题解(C++)
- 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[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
- leetcode452. 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
- leetcode452. Minimum Number of Arrows to Burst Balloons
- [leetcode]452. Minimum Number of Arrows to Burst Balloons