c语言找出数组中两数之和为目标数字
时间: 2024-10-17 10:07:16 浏览: 37
在C语言中,如果你需要找出一个整数数组中两个元素相加等于给定目标值的组合,可以使用哈希表(散列表)来优化搜索过程。这里有一个简单的算法:
```c
#include <stdio.h>
#include <stdbool.h>
// 使用哈希表辅助查找
bool findTwoSum(int arr[], int n, int target) {
// 创建一个空的哈希表
int hash[20001]; // 假设数组元素范围在-10000到10000之间
memset(hash, 0, sizeof(hash));
// 遍历数组,对于每个元素
for (int i = 0; i < n; i++) {
// 计算目标值减去当前元素的差
int complement = target - arr[i];
// 如果这个差已经在哈希表中,说明找到了解
if (hash[complement] != 0) {
printf("Pair found: %d + %d = %d\n", complement, arr[i], target);
return true;
}
// 将当前元素添加到哈希表对应的位置
hash[arr[i]] = i;
}
// 没有找到解就返回false
return false;
}
int main() {
int arr[] = {2, 7, 11, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 9;
if (findTwoSum(arr, n, target)) {
printf("Solution exists.\n");
} else {
printf("No solution exists.\n");
}
return 0;
}
```
在这个程序中,我们遍历数组,对于每个元素计算它的补数(目标值减去该元素)。如果这个补数已经存在于哈希表中,那么我们就找到了一对和为目标值的数;如果没有,就把当前元素及其索引存入哈希表中。如果遍历结束后仍未找到解决方案,则表示不存在这样的组合。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)