|
1 | 1 | class Solution {
|
2 |
| - public int[] successfulPairs(int[] spells, int[] potions, long success) { |
3 |
| - int[] result = new int[spells.length]; |
4 |
| - Arrays.sort(potions); |
5 |
| - for (int i = 0; i < spells.length; i++) { |
6 |
| - int idx = getSuccessIdx(potions, spells[i], success); |
7 |
| - result[i] = potions.length - idx; |
| 2 | + public int[] successfulPairs(int[] spells, int[] potions, long success) { |
| 3 | + Arrays.sort(potions); |
| 4 | + int[] result = new int[spells.length]; |
| 5 | + for (int i = 0; i < spells.length; i++) { |
| 6 | + result[i] = findCountOfSuccessfulPotion(potions, success, (long) spells[i]); |
| 7 | + } |
| 8 | + return result; |
8 | 9 | }
|
9 |
| - return result; |
10 |
| - } |
11 |
| - |
12 |
| - private int getSuccessIdx(int[] potions, int spell, long success) { |
13 |
| - int left = 0; |
14 |
| - int right = potions.length; |
15 |
| - while (left < right) { |
16 |
| - int mid = (left + right) / 2; |
17 |
| - long currSuccess = ((long) potions[mid]) * spell; |
18 |
| - if (currSuccess >= success) { |
19 |
| - right = mid; |
20 |
| - } else { |
21 |
| - left = mid + 1; |
22 |
| - } |
| 10 | + |
| 11 | + private int findCountOfSuccessfulPotion(int[] potions, long success, long spell) { |
| 12 | + int left = 0; |
| 13 | + int right = potions.length - 1; |
| 14 | + int minIdx = Integer.MAX_VALUE; |
| 15 | + while (left <= right) { |
| 16 | + int mid = (left + right) / 2; |
| 17 | + if (potions[mid] * spell >= success) { |
| 18 | + minIdx = Math.min(minIdx, mid); |
| 19 | + right = mid - 1; |
| 20 | + } else { |
| 21 | + left = mid + 1; |
| 22 | + } |
| 23 | + } |
| 24 | + return minIdx == Integer.MAX_VALUE ? 0 : (potions.length - minIdx); |
23 | 25 | }
|
24 |
| - return left; |
25 |
| - } |
26 | 26 | }
|
0 commit comments