For this question, you can simplify it to:
what is the number of pairs that are smaller than equal to
upperminus the number of pairs that are smaller thanlower.
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,
- if
nums[l] + nums[r] <= target,
- then we can simply add
r-ltoans- and increment
lto increasenums[l] + nums[r]- if
nums[l] + nums[r] > target,
- then we can simply decrement
rto decreasenums[l] + nums[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) {
ans += r-l;
++l;
} else {
--r;
}
}
return ans;
}
long long countFairPairs(vector<int>& nums, int lower, int upper) {
sort(nums.begin(), nums.end());
return lessThanTarget(nums, upper) - lessThanTarget(nums, lower-1);
}
};
complexity
- Time:
O(n log(n))wherenis the size ofnums- Space:
O(1)
learnings
- stop forgetting that to find the values between
landr, you can simply find the values smaller thanrand subtract from it the number of values smaller thanl