Created
November 11, 2024 19:18
-
-
Save SuryaPratapK/562a15669ddcfb6edb0ca8137995020a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
#define ll long long | |
public: | |
long long countFairPairs(vector<int>& nums, int lower, int upper) { | |
int n=nums.size(); | |
sort(nums.begin(),nums.end()); | |
ll ans=0; | |
for(int i=0;i<n-1;++i){ | |
int lb = lower_bound(nums.begin()+i+1,nums.end(),lower-nums[i])-nums.begin(); | |
int ub = upper_bound(nums.begin()+i+1,nums.end(),upper-nums[i])-nums.begin(); | |
ans += (ub - lb); | |
} | |
return ans; | |
} | |
}; | |
/* | |
//JAVA | |
import java.util.*; | |
class Solution { | |
public long countFairPairs(int[] nums, int lower, int upper) { | |
int n = nums.length; | |
Arrays.sort(nums); | |
long ans = 0; | |
for (int i = 0; i < n - 1; ++i) { | |
int lb = lowerBound(nums, i + 1, n, lower - nums[i]); | |
int ub = upperBound(nums, i + 1, n, upper - nums[i]); | |
ans += (ub - lb); | |
} | |
return ans; | |
} | |
private int lowerBound(int[] nums, int start, int end, int target) { | |
while (start < end) { | |
int mid = start + (end - start) / 2; | |
if (nums[mid] < target) start = mid + 1; | |
else end = mid; | |
} | |
return start; | |
} | |
private int upperBound(int[] nums, int start, int end, int target) { | |
while (start < end) { | |
int mid = start + (end - start) / 2; | |
if (nums[mid] <= target) start = mid + 1; | |
else end = mid; | |
} | |
return start; | |
} | |
} | |
#Python | |
from bisect import bisect_left, bisect_right | |
class Solution: | |
def countFairPairs(self, nums, lower, upper): | |
nums.sort() | |
ans = 0 | |
n = len(nums) | |
for i in range(n - 1): | |
lb = bisect_left(nums, lower - nums[i], i + 1) | |
ub = bisect_right(nums, upper - nums[i], i + 1) | |
ans += (ub - lb) | |
return ans | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment