|
发表于 2024-9-30 15:10:28
|
显示全部楼层
当然可以,以下是用C语言实现的寻找数组中两个数和为指定目标值的函数:
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct {
- int *arr;
- int size;
- } Result;
- Result two_sum(int* nums, int numsSize, int target) {
- for (int i = 0; i < numsSize - 1; ++i) {
- for (int j = i + 1; j < numsSize; ++j) {
- if (nums[i] + nums[j] == target) {
- int *result = (int *) malloc(2 * sizeof(int));
- result[0] = i;
- result[1] = j;
- Result res = {result, 2};
- return res;
- }
- }
- }
- Result res = {NULL, 0};
- return res;
- }
- int main() {
- int nums1[] = {2, 7, 11, 15};
- int target1 = 9;
- Result res1 = two_sum(nums1, 4, target1);
- if (res1.arr != NULL) {
- printf("Indices: %d, %d\n", res1.arr[0], res1.arr[1]);
- free(res1.arr);
- } else {
- printf("No solution found.\n");
- }
- int nums2[] = {3, 2, 4};
- int target2 = 6;
- Result res2 = two_sum(nums2, 3, target2);
- if (res2.arr != NULL) {
- printf("Indices: %d, %d\n", res2.arr[0], res2.arr[1]);
- free(res2.arr);
- } else {
- printf("No solution found.\n");
- }
- int nums3[] = {3, 3};
- int target3 = 6;
- Result res3 = two_sum(nums3, 2, target3);
- if (res3.arr != NULL) {
- printf("Indices: %d, %d\n", res3.arr[0], res3.arr[1]);
- free(res3.arr);
- } else {
- printf("No solution found.\n");
- }
- return 0;
- }
复制代码
### 解释:
1. **Result 结构体**:定义了一个包含指针和大小的结构体,方便返回下标数组和数组大小。
2. **two_sum 函数**:嵌套的两个循环依次检查数组中每对数的和是否等于目标值。如果找到,返回相应的下标;如果没找到,则返回 `NULL` 指针。
3. **主函数**:测试了三个示例,包含你提到的示例。找到合适的下标后就打印出来。
这个实现方法虽然简单却相对效率较低,两层循环导致时间复杂度为 O(n^2)。如果需要更高效的实现,可以考虑使用哈希表(这个需要用到更复杂的C实现)。希望这样已经足够帮到你了!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|