Skip to content

Commit c6eb111

Browse files
add 2126
1 parent 6881833 commit c6eb111

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ _If you like this project, please leave me a star._ ★
88

99
| # | Title | Solutions | Video | Difficulty | Tag
1010
|-----|----------------|---------------|--------|-------------|-------------
11+
|2126|[Destroying Asteroids](https://leetcode.com/problems/destroying-asteroids/)|[Java](../master/src/main/java/com/fishercoder/solutions/_2126.java) ||Medium||
1112
|2125|[Number of Laser Beams in a Bank](https://leetcode.com/problems/number-of-laser-beams-in-a-bank/)|[Java](../master/src/main/java/com/fishercoder/solutions/_2125.java) ||Medium||
1213
|2124|[Check if All A's Appears Before All B's](https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/)|[Java](../master/src/main/java/com/fishercoder/solutions/_2124.java) ||Easy||
1314
|2120|[Execution of All Suffix Instructions Staying in a Grid](https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/)|[Java](../master/src/main/java/com/fishercoder/solutions/_2120.java) ||Medium||
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.fishercoder.solutions;
2+
3+
import java.util.Arrays;
4+
import java.util.Collections;
5+
import java.util.HashMap;
6+
import java.util.List;
7+
import java.util.Map;
8+
import java.util.Set;
9+
10+
public class _2126 {
11+
public static class Solution1 {
12+
public boolean asteroidsDestroyed(int mass, int[] asteroids) {
13+
Map<Integer, Integer> map = new HashMap<>();
14+
for (int a : asteroids) {
15+
map.put(a, map.getOrDefault(a, 0) + 1);
16+
}
17+
int[] nums = new int[map.keySet().size()];
18+
int i = 0;
19+
for (int key : map.keySet()) {
20+
nums[i++] = key;
21+
}
22+
Arrays.sort(nums);
23+
int startIndex = 0;
24+
long sum = mass;
25+
int upToIndex = binarySearch(sum, nums, startIndex, nums.length - 1);
26+
while (upToIndex < nums.length) {
27+
for (i = startIndex; i <= upToIndex; i++) {
28+
sum += (long) map.get(nums[i]) * nums[i];
29+
}
30+
if (upToIndex == nums.length - 1) {
31+
return true;
32+
}
33+
startIndex = upToIndex + 1;
34+
upToIndex = binarySearch(sum, nums, startIndex, nums.length - 1);
35+
if (startIndex > upToIndex) {
36+
return false;
37+
}
38+
}
39+
return true;
40+
}
41+
42+
private int binarySearch(long sum, int[] nums, int left, int right) {
43+
while (left < right) {
44+
int mid = left + (right - left) / 2;
45+
if (nums[mid] < sum) {
46+
left = mid + 1;
47+
} else if (nums[mid] > sum) {
48+
right = mid - 1;
49+
} else {
50+
return mid;
51+
}
52+
}
53+
return right < nums.length && nums[right] <= sum ? right : left - 1;
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)