452. Minimum Number of Arrows to Burst Balloons

问题:

给定一组[start, end]表示气球左右边界的气球数组,求最少射多少箭,能将所有气球射爆。

射箭位置X,start<=X<=end,则能射破该气球。

Example:
Input:
[[10,16], [2,8], [1,6], [7,12]]
Output:
2

Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).

  

解法:Greedy

435. Non-overlapping Intervals  

本问题,要求最少射箭次数,使得覆盖全部气球。

假设互相不重叠的气球共有n个,那么最少射n次。

也就将该问题转换为,求有多少个不重叠的气球。

即最多有多少个不重叠区间。

 

1.按照end排序sort气球。

2.尽量选择end先结束的作为一个不重叠气球。

3.再用上一个不重叠气球的end,来找下一个start>end的气球,作为下一个不重叠气球。

4.最终找完最多不重叠的气球个数。

 

代码参考:

 1 class Solution {
 2 public:
 3     bool static cmp(vector<int> a, vector<int> b) {
 4         return a[1]<b[1];
 5     }
 6     //to find the minimal number of arrow shots
 7     //means one shots to get max number of ballons which are all overlapping.
 8     //but if there are mostly n non-overlapping ballons, 
 9     //however we choose the shot position, we should at least shot n times
10     // to ensure these n non-overlapping ballons should be all burst.
11     //then this problem == 435
12     int findMinArrowShots(vector<vector<int>>& points) {
13         int count = 1;
14         if(points.empty()) return 0;
15         sort(points.begin(), points.end(), cmp);
16         int pre_end = points[0][1];
17         for(int i=1; i<points.size(); i++) {
18             if(points[i][0]>pre_end) {
19                 count++;
20                 pre_end = points[i][1];
21             }
22         }
23         return count;
24     }
25 };

 

posted @ 2020-09-13 11:01  habibah_chang  阅读(155)  评论(0编辑  收藏  举报