2024/11/14 灵茶题单 二分查找
This commit is contained in:
parent
1c6e61e745
commit
bc2e8eb7ba
|
@ -0,0 +1,40 @@
|
||||||
|
package com.cool.ling_cha_mount.binary_search;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class Num2300 {
|
||||||
|
|
||||||
|
public int[] successfulPairs(int[] spells, int[] potions, long success) {
|
||||||
|
Arrays.sort(potions);
|
||||||
|
int[] res = new int[spells.length];
|
||||||
|
for (int i = 0; i < spells.length; i++) {
|
||||||
|
long target = ((success - 1) / spells[i]);
|
||||||
|
if (target < potions[potions.length - 1]) {
|
||||||
|
res[i] = potions.length - binarySearch(potions, (int)(target + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private int binarySearch(int[] nums, int target) {
|
||||||
|
int left = 0;
|
||||||
|
int right = nums.length - 1;
|
||||||
|
while (left <= right) {
|
||||||
|
int mid = (right - left) / 2 + left;
|
||||||
|
if (nums[mid] >= target) {
|
||||||
|
right = mid - 1;
|
||||||
|
} else {
|
||||||
|
left = mid + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test() {
|
||||||
|
successfulPairs(new int[]{5, 1, 3}, new int[]{1, 2, 3, 4, 5}, 7);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue