-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9204ace
commit a326806
Showing
3 changed files
with
67 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
32 changes: 32 additions & 0 deletions
32
src/page-5/452. Minimum Number of Arrows to Burst Balloons/findMinArrowShots.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { findMinArrowShots } from './findMinArrowShots'; | ||
|
||
describe('452. Minimum Number of Arrows to Burst Balloons', () => { | ||
test('findMinArrowShots', () => { | ||
expect( | ||
findMinArrowShots([ | ||
[10, 16], | ||
[2, 8], | ||
[1, 6], | ||
[7, 12], | ||
]), | ||
).toBe(2); | ||
|
||
expect( | ||
findMinArrowShots([ | ||
[1, 2], | ||
[3, 4], | ||
[5, 6], | ||
[7, 8], | ||
]), | ||
).toBe(4); | ||
|
||
expect( | ||
findMinArrowShots([ | ||
[1, 2], | ||
[2, 3], | ||
[3, 4], | ||
[4, 5], | ||
]), | ||
).toBe(2); | ||
}); | ||
}); |
25 changes: 25 additions & 0 deletions
25
src/page-5/452. Minimum Number of Arrows to Burst Balloons/findMinArrowShots.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
type FindMinArrowShots = (points: number[][]) => number; | ||
|
||
/** | ||
* Accepted | ||
*/ | ||
export const findMinArrowShots: FindMinArrowShots = (points) => { | ||
// Sort the balloons by their end positions | ||
points.sort((a, b) => a[1] - b[1]); | ||
|
||
// Initialize the number of arrows needed and the position of the last arrow shot | ||
let arrows = 1; | ||
let arrowPosition = points[0][1]; | ||
|
||
// Iterate through each balloon | ||
for (let i = 1; i < points.length; i++) { | ||
// If the current balloon's start is greater than the last arrow position | ||
if (points[i][0] > arrowPosition) { | ||
// We need a new arrow | ||
arrows += 1; | ||
arrowPosition = points[i][1]; // Update the arrow position to the current balloon's end | ||
} | ||
} | ||
|
||
return arrows; | ||
}; |