题意:每一个气球在一个区间[s,e]内,从某一个点射出一支箭,可以将经过该点的气球引爆,问引爆所有气球至少需要多少只箭。
思路:按起始点将所有气球排序,引爆一只气球最佳的地点在这支气球的终点,记为cur_end,因为这样能够引爆更多的气球,当另外一只气球b的区间与引爆点重叠时,此时的最佳引爆点成了min(cur_end, b.end).如果该气球的区间不与此时的引爆点重叠时,这时需要另外开一个引爆点。
时间复杂度:O(N)
C++代码:
class Solution {
public:
struct node{
int s, e;
node(int s, int e): s(s), e(e){}
bool operator < (node a){
return s < a.s;
}
};
vector<node> bl;
int findMinArrowShots(vector<vector<int>>& points) {
for(int i = 0; i < points.size(); i++){
bl.push_back(node(points[i][0], points[i][1]));
}
sort(bl.begin(), bl.end());
int res = 0;
bool start = false;
int cur_end;
for(int i = 0; i < points.size(); i++){
if(start == false){
cur_end = bl[i].e;
res++;
}else{
if(cur_end > bl[i].e){
cur_end = bl[i].e;
}
else if (bl[i].s > cur_end){
cur_end = bl[i].e;
res++;
}
}
start = true;
}
return res;
}
};
//[[2,5],[1,8],[3,10],[4,6],[7,9]]