[LeetCode] 2563. Count the Number of Fair Pairs

Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs.

A pair (i, j) is fair if:
0 <= i < j < n, and
lower <= nums[i] + nums[j] <= upper

Example 1:
Input: nums = [0,1,7,4,4,5], lower = 3, upper = 6
Output: 6
Explanation: There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5).

Example 2:
Input: nums = [1,7,9,2,5], lower = 11, upper = 11
Output: 1
Explanation: There is a single fair pair: (2,3).

Constraints:
1 <= nums.length <= 105
nums.length == n
-109 <= nums[i] <= 109
-109 <= lower <= upper <= 109

统计公平数对的数目。

给你一个下标从 0 开始、长度为 n 的整数数组 nums ,和两个整数 lower 和 upper ,返回 公平数对的数目 。
如果 (i, j) 数对满足以下情况,则认为它是一个 公平数对 :
0 <= i < j < n,且
lower <= nums[i] + nums[j] <= upper

思路

注意我们要找的 i 和 j 满足lower <= nums[i] + nums[j] <= upper 的数对的个数,而且是闭区间。那么我们可以把这个条件改写为找到 i 和 j 满足 nums[i] + nums[j] <= upper 的个数减去 nums[i] + nums[j] <= lower - 1的个数。

这道题的思路跟 611 题,2824 题很像,可以先做这两题。做完这两题再做本题你就会发现我们还是可以对 input 数组排序,排序之后我们用一个 helper 函数分别去找 nums[i] + nums[j] <= upper 的个数和nums[i] + nums[j] <= lower - 1的个数。

复杂度

时间O(n^2)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public long countFairPairs(int[] nums, int lower, int upper) {
Arrays.sort(nums);
return helper(nums, upper) - helper(nums, lower - 1);
}

private long helper(int[] nums, int target) {
long res = 0;
int left = 0;
int right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum <= target) {
res += right - left;
left++;
} else {
right--;
}
}
return res;
}
}

相关题目

1
2
3
4
259. 3Sum Smaller
611. Valid Triangle Number
2563. Count the Number of Fair Pairs
2824. Count Pairs Whose Sum is Less than Target

[LeetCode] 2563. Count the Number of Fair Pairs
https://shurui91.github.io/posts/1345396682.html
Author
Aaron Liu
Posted on
November 23, 2023
Licensed under