📅  最后修改于: 2023-12-03 15:23:04.267000             🧑  作者: Mango
The ISRO CS 2017 - Question 9 is a programming question from the ISRO Computer Science 2017 exam. In this question, we are given a sorted array of integers and we need to find the number of pairs of integers in the array whose sum is equal to a given number.
Given a sorted array of integers arr
and a number num
, find the number of pairs of integers in the array whose sum is equal to num
.
arr
- An array of n integers (1 <= n <= 10^5) where each integer a_i (-10^9 <= a_i <= 10^9) is sorted in non-descending order.num
- An integer (−10^9 <= num <= 10^9).num
.Input:
arr = [1, 2, 3, 4, 5, 6, 8, 9]
num = 7
Output:
2
Explanation: The two pairs are (1,6) and (2,5).
We can solve this problem using a two-pointer approach. We start by initializing two pointers, one at the beginning of the array and the other at the end. We then check the sum of the values pointed to by the two pointers. If the sum is equal to num
, we increment our count of pairs and move both pointers. If the sum is less than num
, we move our left pointer to the right. If the sum is greater than num
, we move our right pointer to the left. We continue doing this until both pointers meet.
def count_pairs(arr, num):
n = len(arr)
count = 0
i, j = 0, n - 1
while i < j:
if arr[i] + arr[j] == num:
count += 1
i += 1
j -= 1
elif arr[i] + arr[j] < num:
i += 1
else:
j -= 1
return count
The above code is written in Python and uses the two-pointer approach to find the number of pairs whose sum is equal to `num`. The time complexity of this solution is O(n) and the space complexity is O(1).