Sponsored
Sponsored
This approach leverages sorting and a two-pointer technique to efficiently find the number of fair pairs. By sorting the array, we bring potential fair pairs closer, simplifying the conditions checking. Two pointers are then used to find suitable pairs within the bounds.
First, sort the array nums
. As we iterate through each element as one half of the pair, use two pointers to find elements that complete the pair within the given range of sums.
Time Complexity: O(n log n), where the sorting step dominates the complexity. Each binary search operation runs in O(log n).
Space Complexity: O(1), as we sort in-place.
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5class Solution {
6public:
7 int countFairPairs(std::vector<int>& nums, int lower, int upper) {
8 std::sort(nums.begin(), nums.end());
9 int count = 0;
10 for (int i = 0; i < nums.size(); ++i) {
11 auto low = std::lower_bound(nums.begin() + i + 1, nums.end(), lower - nums[i]);
12 auto high = std::upper_bound(nums.begin() + i + 1, nums.end(), upper - nums[i]);
13 count += high - low;
14 }
15 return count;
16 }
17};
18
19int main() {
20 Solution sol;
21 std::vector<int> nums = {0, 1, 7, 4, 4, 5};
22 int result = sol.countFairPairs(nums, 3, 6);
23 std::cout << "Number of fair pairs: " << result << std::endl;
24 return 0;
25}
In C++, the function utilizes std::lower_bound
and std::upper_bound
to efficiently find the number of valid pairs. This makes use of STL functions for the binary search operations within a sorted vector.
A simpler, brute-force approach involves examining every possible pair (i, j) to determine if it fits the 'fair pair' criteria. While this method is easier to understand and implement, it becomes inefficient as the input size increases.
Time Complexity: O(n^2), as it examines every possible pair.
Space Complexity: O(1), since no additional space is utilized.
1
public class Solution {
public int CountFairPairs(int[] nums, int lower, int upper) {
int count = 0;
for (int i = 0; i < nums.Length; i++) {
for (int j = i + 1; j < nums.Length; j++) {
int sum = nums[i] + nums[j];
if (sum >= lower && sum <= upper) {
count++;
}
}
}
return count;
}
public static void Main() {
Solution sol = new Solution();
int[] nums = {0, 1, 7, 4, 4, 5};
int result = sol.CountFairPairs(nums, 3, 6);
Console.WriteLine("Number of fair pairs: " + result);
}
}
The C# solution systematically evaluates all index pairs using nested loops to ensure their sum fits within the set bounds.