Implement the method countPairsWithSum that counts index pairs whose values add up to a target.
Count pairs (i, j) where i < j and nums[i] + nums[j] == target.
The task is designed to test careful handling of edge cases, not only the most common input.
- Use only the first
sizeelements. - Duplicate values can create multiple valid index pairs.
- Return the number of pairs, not the pairs themselves.
Example 1
Input
nums (int[]) =
[1,5,7,-1,5]size (int) =
5target (int) =
6Returns (int)
3Example 2
Input
nums (int[]) =
[1,1,1,1]size (int) =
4target (int) =
2Returns (int)
6Example 3
Input
nums (int[]) =
[2,4,3,5,7]size (int) =
5target (int) =
9Returns (int)
2While scanning, add the number of earlier values equal to target - current, then record the current value.
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run