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

This commit is contained in:
Cool 2024-11-18 18:04:40 +08:00
parent 0683d87b58
commit 5331e3c5b4
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 Num2563 {
public long countFairPairs(int[] nums, int lower, int upper) {
long res = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
int m = lowerBound(nums, i, upper - nums[i] + 1);
int n = lowerBound(nums, i, lower - nums[i]);
res += m - n;
}
return res;
}
private int lowerBound(int[] nums, int right, int target) {
int left = -1;
while (left + 1 < right) {
int mid = (left + right) >>> 1;
if (nums[mid] < target) {
left = mid;
} else {
right = mid;
}
}
return right;
}
}