|
| 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