使用 C++ 统计数组中和值也存在于数组中的不同对的数量


假设我们有一个整数数组 arr[],它可以是任意大小,任务是计算给定数组中不同对的数量,这些对的和也存在于同一个数组中。

数组是一种数据结构,可以存储相同类型元素的固定大小的顺序集合。数组用于存储数据集合,但通常将数组视为相同类型变量的集合更有用。

需要记住的要点

  • 无论元素顺序如何,一对元素只会被计算一次。例如,(3,2) 和 (2,3) 将被计为 1。

  • 如果数组中某个数字出现多次,则将被精确地考虑两次以形成一对。例如,如果数组的元素为 {2, 2, 2, 2},则对将为 (2,2),并且将被计为 1。

例如

Input − int arr = {6, 4, 10, 14}
Output − count is 2

解释 - 数组中和值存在的对为 (6,4) 和 (10,4),所以计数为 2

Input − int arr = {6, 6, 6 ,6, 6, 13}
Output − count is 0

解释 - 数组中没有和值也在数组中的对。所以,计数为 0。

下面程序中使用的算法如下

  • 创建一个数组,例如 arr[]

  • 使用 length() 函数计算数组的长度,该函数将根据数组中的元素返回一个整数值。

  • 取一个临时变量来存储元素的计数。

  • 创建一个 map 类型的变量,例如 mp

  • 开始循环,从 i=0 开始,到 i 小于数组大小结束

  • 创建一个另一个存储对的 map 类型的变量,例如 par

  • 开始循环,从 i=0 开始,到 i 小于数组大小结束

  • 在循环内部,开始另一个循环,从 j=i+1 开始,到 j 小于数组大小结束

  • 在循环内部,检查如果 mp[arr[i]+arr[j]] > 0 并且 pr[{arr[i], arr[j] }] =0,则将计数加 1

  • 将 par[{ arr[i], arr[j] }] 加 1

  • 将 par[{ arr[j], arr[i] }] 加 1

  • 返回计数

  • 打印结果。

示例

 在线演示

#include <iostream>
#include <map>
using namespace std;
// Returns number of pairs in ar[0..n-1] with
// sum equal to 'sum'
int countpairs(int ar[], int n){
   // Store counts of all elements in map m
   // to find pair (ar[i], sum-ar[i])
   // because (ar[i]) + (sum - ar[i]) = sum
   map<int, int> mymap;
   for (int i = 0; i < n; i++){
      mymap[ar[i]]++;
   }
   // To remove duplicate items we use result map
   map<pair<int, int>, int> p;
   int result = 0;
   // Considering all pairs
   for (int i = 0; i < n; i++){
      for (int j = i + 1; j < n; j++){
         // If sum of current pair exists
         if (mymap[ar[i] + ar[j]] > 0 && p[{ ar[i], ar[j] }] ==0){
            result++;
         }
         // Inserting the current pair both ways to avoid
         // duplicates.
         p[{ ar[i], ar[j] }]++;
         p[{ ar[j], ar[i] }]++;
      }
   }
   return result;
}
// main function
int main(){
   int ar[] = { 6, 4, 10, 14 };
   int n = sizeof(ar) / sizeof(ar[0]);
   cout << "count is "<<countpairs(ar, n);
   return 0;
}

输出

如果我们运行以上代码,我们将得到以下输出:

count is 2

更新于:2020年5月15日

451 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.