gpt4 book ai didi

c++ - 计算给定总和的对

转载 作者:太空宇宙 更新时间:2023-11-04 15:57:50 24 4
gpt4 key购买 nike

给定一个整数数组和一个数字“sum”,找出数组中和等于“sum”的整数对的数量。这是 Geeks for Geeks 的解决方案:

// 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)
{
unordered_map<int, int> m;

// Store counts of all elements in map m
for (int i=0; i<n; i++)
m[arr[i]]++;

int twice_count = 0;

// iterate through each element and increment the
// count (Notice that every pair is counted twice)
for (int i=0; i<n; i++)
{
twice_count += m[sum-arr[i]];

// if (arr[i], arr[i]) pair satisfies the condition,
// then we need to ensure that the count is
// decreased by one such that the (arr[i], arr[i])
// pair is not considered
if (sum-arr[i] == arr[i])
twice_count--;
}

// return the half of twice_count
return twice_count/2;
}

// 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;
}

我的大问题是,sum-arr 是什么?它没有声明,所以它必须用 C++ 构建。但是,我找不到它的任何文档,而且我不确定它是如何工作的。我正在尝试遵循代码,但 sum-arr 值没有意义。

到达 [1,5,8,-1,5]

米 [0,1,0,0,0]

求和 [5,1,-2,7,1]

最佳答案

Expression, sum - arr[n] which yields the value stored in the nth position of the array.

在这里,n 处的 arr 值(这里是 i 指向的位置,因为它是 arr[i] )减去 sum 的值.

给定,你说,

int arr[] = { 1, 5 , 8, -1, 5 }

int sum = 6

然后,例如,取i作为0...

arr[i]表示为 arr[0]这意味着指向数组 arr 中的第一个元素 (0) .这里的值为 1。

然后从 6 中减去 1,我们得到 5

另一方面,sum - arr是整数( int )与指针( int arr[] 将在程序内部变为 int * arr )的减法,事实上,这是不可能的,因为 super 指针比子指针大。 ..

但是,您可以这样做,sum - *arr (这称为取消引用)。

最后的话,

只是为了减少所有这些与使用指针和所有东西的混淆,只需使用 std::vector<type> (示例: std::vector<int> arr; ),这是 C++ 中的常见做法,更重要的是,它也像它们一样工作! (尽管如此,您还是坚持在 C 语言中使用指针!)。

祝你好运!

关于c++ - 计算给定总和的对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52703807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com