繁体   English   中英

创建一个 C++ 程序,以查找给定整数数组中总和等于指定数的整数对数

[英]Create a C++ program to find the number of pairs of integers in a given array of integers whose sum is equal to a specified number

编写一个 C++ 程序来查找给定整数数组中总和等于指定数的整数对的数量。 该程序将要求用户输入 10 个数字并检查一对整数是否等于用户指定的数字。

您的程序将显示数组中整数对的位置及其对应的值。

样品输入:

Enter an array of integers: 75 90 100 32 1 55 92 123 56 10
Sum of pairs of integers: 101

样品 OUTPUT:

The location of the pair of integers are number[2] and number[4] and the values are 
100 and 1, respectively  

根据您希望如何实现它,您可以考虑类似于以下的递归方法:

void pairAddToK(vector<int> L, int left, int right, int K) {
    if (left == right) // Our base case
       return;
    if (left + 1 == right) { // 2 elements, check if they add to K
       if (L[left] + L[right] == K)
          cout << L[left] << " + " << L[right] << " = " << K << endl;
    }

    int mid = (left + right) / 2; // General case, use recursion to divide and conquer
    
    pairAddToK(L, left, mid, K);
    pairAddToK(L, mid + 1, right, K);

    for (int i = left; i <= mid; i++) // Check for pairs from both halves
       for (int j = mid + 1; j <= right; j++)
           if (L[i] + L[j] == K)
              cout << L[i] " + " << L[j] << " = " << K << endl;
}

这些方面的东西应该起作用。 我没有对此进行测试,只在 StackOverflow 答案框中写了这个,所以如果需要澄清,请告诉我。

您将需要一个嵌套的 while 循环或嵌套的 for 循环。

检查是否 arr[0] + arr[1] == sum_of_pair_of_int 如果是,则将其插入对...数组也可以工作。 然后检查 arr[0] + arr[2]。 重复阵列的 rest。 然后从 arr[1] + arr[2] 开始,然后是 arr[1] + arr[3] 等。

如果您有更具体的问题,那将更有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM