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:

1
2
3
4
5
6
7
8
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).

思路

将气球排序,维护一个指向当前气球最小结束值的指针。当一个气球的起始值大于该最小结束值,将该气球置为当前气球。然后将之前的气球戳爆!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def findMinArrowShots(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
points.sort()
low = 0
high = 0
count = 0
if (points):
low = points[0][0]
high = points[0][1]
else:
return 0
for point in points:
if (point[0] > high):
count += 1
low = point[0]
high = point[1]
elif (point[1] < high and point[0] > low):
high = point[1]
return count+1

参考资料和测试用例:

[[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
[[9,12],[1,10],[4,11],[8,12],[3,9],[6,9],[6,7]]
https://discuss.leetcode.com/topic/72901/a-concise-template-for-overlapping-interval-problem