There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points
where points[i] = [xstart, xend]
denotes a balloon whose horizontal diameter stretches between xstart
and xend
. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart
and xend
is burst by an arrow shot at x
if xstart <= x <= xend
. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array points
, return the minimum number of arrows that must be shot to burst all balloons.
Example 1:
1 2 3 4 5 |
<strong>Input:</strong> points = [[10,16],[2,8],[1,6],[7,12]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. |
Example 2:
1 2 3 |
<strong>Input:</strong> points = [[1,2],[3,4],[5,6],[7,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One arrow needs to be shot for each balloon for a total of 4 arrows. |
Example 3:
1 2 3 4 5 |
<strong>Input:</strong> points = [[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/
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 26 27 28 29 30 31 |
class Solution { public int findMinArrowShots(int[][] points) { //sort points based on Xstart (ascending) //if Xstart is equal then sort based on Xend (ascending) Arrays.sort(points, new Comparator<int[]>(){ public int compare(int[] a, int [] b){ int res = Integer.compare(a[0], b[0]); if(res==0){ res = Integer.compare(a[1], b[1]); } return res; } }); int[] prev = points[0]; int count = 1; for(int i=1;i<points.length;i++){ //if the points overlapped if(prev[1] >= points[i][0]){ prev[0] = Math.max(prev[0], points[i][0]); prev[1] = Math.min(prev[1], points[i][1]); } //if the points are non overlapping //then increment the count else { prev = points[i]; count++; } } return count; } } |