# 2563. Count the Number of Fair Pairs
###### tags: `Leetcode` `Medium` `Two Pointers`
Link: https://leetcode.com/problems/count-the-number-of-fair-pairs/description/
## 思路
```
Number of pairs with sum >= lower and <= upper
= (Number of pairs with sum <= upper) - (Number of pairs with sum < lower)
```
双指针找出所有和小于某个值的pair数
## Code
```java=
class Solution {
public long countFairPairs(int[] nums, int lower, int upper) {
Arrays.sort(nums);
return countLess(nums, upper)-countLess(nums, lower-1);
}
public long countLess(int[] nums, int bound){
long res = 0;
int i = 0, j = nums.length-1;
while(i<j){
while(i<j && nums[i]+nums[j]>bound) j--;
res += j-i;
i++;
}
return res;
}
}
```
```python=
class Solution:
def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
nums.sort()
def countLessThan(nums, target):
ans = 0
i, j = 0, len(nums)-1
while i<j:
while i<j and nums[i]+nums[j]>target: j-=1
ans += j-i
i += 1
return ans
return countLessThan(nums, upper)-countLessThan(nums, lower-1)
```