2563: Count-the-Number-of-Fair-Pairs
Medium
For this question, you can simplify it to:
To accomplish this, we can create a
two-pointers function that calculates the
number of pairs that are smaller than equal to
target
.
In this function, we have 2 pointers; l
points to
the beginning of nums
, while r
points to
the end of nums
, and an ans
variable to
track the . Now, while l < r
,
Code:
class Solution {
public:
long long lessThanTarget(vector<int>& nums, int target) {
long long l = 0, r = nums.size()-1, ans = 0;
while (l < r) {
if (nums[l] + nums[r] <= target) {
+= r-l;
ans ++l;
} else {
--r;
}
}
return ans;
}
long long countFairPairs(vector<int>& nums, int lower, int upper) {
(nums.begin(), nums.end());
sortreturn lessThanTarget(nums, upper) - lessThanTarget(nums, lower-1);
}
};