1
2
3
4
5
|
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:2Explanation: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).
|
题意:一堆气球,X轴方向,有一个起始位置和结束位置。现在准备射箭打气球,问最少需要几只箭才能射破全部气球。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
class
Solution {
public
int
findMinArrowShots(
int
[][] points) {
if
(points ==
null
|| points.length ==
0
|| points[
0
].length ==
0
) {
return
0
;
}
int
row = points.length;
int
col = points[
0
].length;
Arrays.sort(points,
new
Comparator<
int
[]>() {
public
int
compare(
int
[] a,
int
[] b) {
return
a[
1
] - b[
1
];
}
});
int
start = points[
0
][
0
], end = points[
0
][
1
], ret =
1
;
for
(
int
i =
1
; i < row; i++){
if
(points[i][
0
] <= end){
//end = points[i][1];
//start = points[i][0];
continue
;
}
ret++;
end = points[i][
1
];
}
return
ret;
}
}
|
第一种方法是固定气球的终止位置,然后从前往后遍历,当遇到的气球的起始位置小于之前的终止位置,则表示可以一支箭射破这些气球。当大于的时候,则需要一只新箭。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public
class
Solution {
public
int
findMinArrowShots(
int
[][] points) {
if
(points ==
null
|| points.length <
1
)
return
0
;
Arrays.sort(points, (a, b)->(a[
0
]-b[
0
]));
int
result =
1
;
int
end = points[
0
][
1
];
for
(
int
i =
1
; i < points.length; i ++) {
if
(points[i][
0
] > end) {
result ++;
end = points[i][
1
];
}
else
{
end = Math.min(end, points[i][
1
]);
}
}
return
result;
}
}
|
第二种方法是固定气球的起始位置,比较新气球的起始位置和前气球的终止位置,不断缩小气球的公共区域,直到最后不能缩小位置。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1969945