C语言给定一个整数数组 nums 和一个目标整数值 target,请你在该数组中找出 和为目标值target的那两个整数,并返回它们的数组下标。 假设每种输入只会对应一个答案,每个元素可以多次使用。 可以按任意顺序返回答案。 考虑多解和无解情况 不用哈希表
时间: 2024-10-06 12:01:49 浏览: 34
在C语言中,你可以通过两层循环来解决这个问题,利用暴力搜索的方法。这是一个双指针的解决方案,通常用于数组求解的问题,例如寻找两个数之和等于目标值的情况:
```c
#include <stdio.h>
// 定义一个函数找到两个数的索引,返回值是一个结构体包含两个下标
typedef struct {
int index1;
int index2;
} IndexPair;
IndexPair findTwoSum(int nums[], int n, int target) {
// 初始化两个指针,i 指向第一个元素,j 指向最后一个元素
int i = 0, j = n - 1;
while (i < j) {
// 当前元素和等于目标值时,返回结果
if (nums[i] + nums[j] == target) {
return (IndexPair){i, j};
}
// 如果和小于目标值,移动较小的那个指针
if (nums[i] + nums[j] < target) {
i++;
} else { // 如果和大于目标值,移动较大的那个指针
j--;
}
}
// 如果找不到符合条件的两个数,返回无解(默认或自定义错误处理)
return (IndexPair){-1, -1}; // 或者你可以返回一个特殊的结构体表示无解
}
int main() {
int nums[] = {2, 7, 11, 15}, target = 9;
IndexPair result = findTwoSum(nums, sizeof(nums) / sizeof(nums[0]), target);
if (result.index1 != -1 && result.index2 != -1) {
printf("The two numbers with sum %d are at indices (%d, %d)\n", target, result.index1, result.index2);
} else {
printf("No pair found with sum %d.\n", target);
}
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://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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)