2024/11/18 灵茶题单 二分查找
This commit is contained in:
parent
0683d87b58
commit
5331e3c5b4
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue