#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.
Input:
[[10,16], [2,8], [1,6], [7,12]]
Output:
2
分享一种我的很傻的做法
int findMinArrowShots(vector < pair < int, int>>& points) {
pair < int,int>pre(-1,-1);//前面的公共区域
if(points.size()==0) return 0;
int ans=1;
sort(points.begin(),points.end());
for(int i=1;i < points.size();i++)
{
if(points[i].first>points[i-1].second)//没有交集
{
pre=make_pair(-1,-1);
ans++;
continue;
}
else
{
pair<int,int>cros;
cros=make_pair(points[i].first,min(points[i].second,points[i-1].second));//计算公共区域
if(pre.first==-1)//看前面有没有公共区域
{
pre=cros;
continue;
}
else
{
if((cros.first>=pre.first)&&(cros.first<=pre.second))//前面存在公共区域,看两个有没有交集,有交集,
{
pre=make_pair(cros.first,min(cros.second,pre.second));//有交集,那么缩小公共区域,继续判断
continue;
}
else//没有交集,那么这一个要射,前面列为没有交集。
{
pre=make_pair(-1,-1);
ans++;
continue;
}
}
}
}
return ans;
}
其实这道题,当pair.first排序之后,下一个气球的first>=pre.first。
所以只用考虑是不是还在这个公共区域里面就可以啦。如果比边界小,就缩小边界。
public int findMinArrowShots(vector < pair < int, int>>& points) {
if( points.size==0) return 0;
sort(points.begin(),points.end());
int minArrows = 1;
int arrowLimit = points[0].second;
for(int i=1;i < points.size();i++) {
pair < int,int > baloon = points[i];
if(baloon.first<=arrowLimit) {
arrowLimit=min(arrowLimit, baloon.second);
} else {
minArrows++;
arrowLimit=baloon.second;
}
}
return minArrows;
}