LeetCode_452.Minimum Number of Arrows to Burst Balloons
原题:There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it’s horizontal, y-coordinates don’t matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.
An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.
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).
解析:题意是,给我们一个表,里面包含了一些二元对元素,每个二元对的第一个参数表示气球的起始x轴,第二个参数 表示气球的结束x轴。让我发射若干箭,若箭发射的x轴在二元对里,则这个气球被击破(如发射箭x = 3,则[2,4],[1,3],[1,9]都会被击中),让我们求发射最少的箭矢数量。
这题可以用我们课堂上所学习的贪心算法,求当前情况下最优解,若对于两对二元对[a,b]、[c,d],若b>c,b< d,则这两个气球必然可以为同一个箭所射中(只需令箭矢x = b),所以将表根据元素的第二个参数从小到大排序,保证b< d,再对每个元素进行判断,若b< c,则可以通过一个箭矢射穿他们。
具体代码如下:
class Solution {
public:
int findMinArrowShots(vector<pair<int, int>>& points) {
vector<pair<int, int>> points_temp(points);
sort(points_temp.begin(),points_temp.end(),cmp);
int arw = -1,count = 0;
for(int i = 0;i < points_temp.size();i ++){
if(arw != -1 && points_temp[i].first <= arw)continue;
arw = points_temp[i].second;
count++;
}
return count;
}
private:
static bool cmp(pair<int, int> a, pair<int, int> b){
if(a.second != b.second)return a.second < b.second;
else return a.first < b.first;
}
};
这里有一个小问题,就是比较函数cmp,一开始直接写没有加“static”,会提示如下
因此根据他的提示加了“static”就好了,后来经过上网查找,发现是因为:非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法在sort中调用非静态成员函数。