ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 计算给定总和的对 > 原文: [https://www.geeksforgeeks.org/count-pairs-with-given-sum/](https://www.geeksforgeeks.org/count-pairs-with-given-sum/) 给定一个整数数组和一个数字“和”,找到该数组中总和等于“和”的整数对的数量。 **示例**: ``` Input : arr[] = {1, 5, 7, -1}, sum = 6 Output : 2 Pairs with sum 6 are (1, 5) and (7, -1) Input : arr[] = {1, 5, 7, -1, 5}, sum = 6 Output : 3 Pairs with sum 6 are (1, 5), (7, -1) & (1, 5) Input : arr[] = {1, 1, 1, 1}, sum = 2 Output : 6 There are 3! pairs with sum 2. Input : arr[] = {10, 12, 10, 15, -1, 7, 6, 5, 4, 2, 1, 1, 1}, sum = 11 Output : 9 ``` 预期时间复杂度`O(n)` 一个**简单解决方案**遍历每个元素,并检查数组中是否有另一个数字可以添加到该数字以求和。 ## C++ ```cpp // C++ implementation of simple method to find count of // pairs with given sum. #include <bits/stdc++.h> using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount(int arr[], int n, int sum) {     int count = 0; // Initialize result     // Consider all possible pairs and check their sums     for (int i=0; i<n; i++)         for (int j=i+1; j<n; j++)             if (arr[i]+arr[j] == sum)                 count++;     return count; } // Driver function to test the above function int main() {     int arr[] = {1, 5, 7, -1, 5} ;     int n = sizeof(arr)/sizeof(arr[0]);     int sum = 6;     cout << "Count of pairs is "           << getPairsCount(arr, n, sum);     return 0; } ```