Problem description:

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).

Solution:

The question is saying that we have many balloons, which might overlap, and how many arrows make them burst.
Take the example from question, the graph would look like this.

1
2
3
    ---(2,8)---            ---(10,16)---
---(1,6)--- ---(7,12)---
|-------------------------------------------|

From the graph, it’s easy to come out with the answer that we need two arrows. So let’s transfer it to code.

  1. We need to sort the input points, and we can use STL sorting directly. Since the STL sorting pairs will sort the first element in advance, if the first element are equal, then it’ll sort based on second element.
  2. We can see that if the end value overlaps other’s start value, we can use one arrow to burst them.
  3. If a balloon’s start is greater than current end value, then we need a new arrow.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int findMinArrowShots(vector<pair<int, int>>& points) {
if(points.empty()) return 0;
sort(points.begin(), points.end());

int res= 1, end= points[0].second;
for(int i= 1; i< points.size(); i++){
if(points[i].first<= end)
//can cover ith balloon
end= min(end, points[i].second);
else{
//can not use previous arrow to shot current balloon, need new arrow
res++;
end= points[i].second;
}
}
return res;
}
};

time complexity: $O(nlogn)$
reference:
http://www.cnblogs.com/grandyang/p/6050562.html
https://goo.gl/oBHFYw