一个长度为n的数组中的数互不相同,求其中和为0的数对的个数
时间: 2024-04-14 09:28:17 浏览: 226
要求一个长度为n的数组中和为0的数对的个数,可以使用哈希表来解决这个问题。以下是一个C++的示例代码:
```cpp
#include <iostream>
#include <unordered_map>
#include <vector>
int countZeroSumPairs(std::vector<int>& nums) {
int count = 0;
std::unordered_map<int, int> numFreq;
// 统计每个数出现的频率
for (int num : nums) {
numFreq[num]++;
}
// 遍历数组中的每个数对
for (int num : nums) {
int complement = -num; // 补数
// 如果补数存在且不等于当前数,则计算对数
if (numFreq.find(complement) != numFreq.end() && num != complement) {
count += numFreq[complement];
}
}
return count / 2; // 每对数被计算了两次,需要除以2
}
int main() {
int n;
std::cout << "请输入数组长度: ";
std::cin >> n;
std::vector<int> nums(n);
std::cout << "请输入数组元素: ";
for (int i = 0; i < n; i++) {
std::cin >> nums[i];
}
int pairsCount = countZeroSumPairs(nums);
std::cout << "和为0的数对的个数为: " << pairsCount << std::endl;
return 0;
}
```
这段代码中,`countZeroSumPairs`函数使用哈希表来统计数组中每个数出现的频率。然后,它遍历数组中的每个数,计算其补数(即与之相加为0的数),并检查补数是否存在且不等于当前数。如果满足条件,则将补数的频率加到计数器中。最后,返回计数器除以2的结果,因为每对数被计算了两次(例如,对于数对(1, -1),1和-1都会被计算)。
你可以根据需要修改输入输出部分,以适应你的实际情况。
阅读全文
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)