2024/11/15 灵茶题单 二分查找

This commit is contained in:
Cool 2024-11-15 13:19:22 +08:00
parent bc2e8eb7ba
commit 59f449b22a
1 changed files with 31 additions and 0 deletions

View File

@ -0,0 +1,31 @@
package com.cool.ling_cha_mount.binary_search;
import java.util.Arrays;
public class Num2389 {
public int[] answerQueries(int[] nums, int[] queries) {
Arrays.sort(nums);
int[] res = new int[queries.length];
for (int i = 1; i < nums.length; i++) {
nums[i] += nums[i - 1];
}
for (int i = 0; i < queries.length; i++) {
res[i] = binarySearch(nums, queries[i] + 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 (target <= nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
}