【LeetCode】452. Minimum Number of Arrows to Burst Balloons 解题记录
问题描述
There are some 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. The start is always smaller than the end.
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 traveling up infinitely.
Given an array points where points[i] = [xstart, xend], return the minimum number of arrows that must be shot to burst all balloons.
测试样例
1 | Input: points = [[10,16],[2,8],[1,6],[7,12]] |
1 | Input: points = [[1,2],[3,4],[5,6],[7,8]] |
1 | Input: points = [[1,2],[2,3],[3,4],[4,5]] |
说明
1 | 1 <= points.length <= 10^4 |
解题
思路
区间重叠情况,一般可以使用贪心算法。
把所有的区间按照右边界进行排序。遍历时只要向当前气球的右边界射箭,就能打破尽可能多的气球。然后依次移动射箭的位置,进行统计即可。
补充:
- 先排序
- 贪心算法
- 时间复杂度
O(nlogn)
(排序)
代码
1 | import java.util.Arrays; |