力扣2563.统计公平数对的数目
文章目录
- 题目介绍
- 解法
题目介绍
解法
红蓝染色体法
class Solution {
public long countFairPairs(int[] nums, int lower, int upper) {
long res = 0;
Arrays.sort(nums);
for(int i = 0; i < nums.length -1; i++){
int left = lowerBound(nums,lower - nums[i],i + 1); // >= lower-nums[i] 的位置
int right = lowerBound(nums,upper - nums[i] + 1,i + 1) - 1; // <= upper-nums[j]的位置
res = res + right - left + 1;
}
return res;
}
public int lowerBound(int[] nums, int target, int startidx) {
int left = startidx, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
}