C语言-找出数组中两个数字的和为该数字的位置

1.题目要求

复制代码
(语言: C)给定一组整形数组和一个数字,找出数组中两个数字的和为该数字的位置,例如
数组{2, 7, 11, 15}, 数字9,输出为1,2

函数原型为:
int *twoSum(int numbers[], int n, int target) 
//函数中定义一个动态数组,用于存储这两个数字的下标,最后返回动态数组的首地址。
//不要忘了在主函数中要释放动态数组占用的内存。

输入输出格式为
printf("Please input the array size\n");
scanf("%d");
for()
 {
        printf("Please input the %d-th number\n",i);
        scanf("%d");
 }
    printf("Please input the target number\n");
    scanf("%d");
    if (存在)
    {
        printf("The index1: %d; the index2: %d\n");
        printf("values are %d and %d.\n");
    }else
    {
        printf("result is not available!\n");
    }

程序运行如下
Please input the array size
3
Please input the 0-th number
1
Please input the 1-th number
2
Please input the 2-th number
3
Please input the target number
3
The index1: 1; the index2: 2
values are 1 and 2.

2.代码实现

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

int *twoSum(int numbers[], int n, int target) {
    int *result = (int *)malloc(2 * sizeof(int));
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (numbers[i] + numbers[j] == target) {
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
    free(result);
    return NULL;
}

int main() {
    int n;
    printf("Please input the array size\n");
    scanf("%d", &n);

    int *numbers = (int *)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) {
        printf("Please input the %d -th number\n", i);
        scanf("%d", &numbers[i]);
    }

    int target;
    printf("Please input the target number\n");
    scanf("%d", &target);

    int *result = twoSum(numbers, n, target);
    if (result) {
        printf("The index1: %d; the index2: %d\n", result[0], result[1]);
        printf("values are %d and %d.\n", numbers[result[0]], numbers[result[1]]);
        free(result);
    } else {
        printf("result is not available!\n");
    }

    free(numbers);
    return 0;
}
相关推荐
纨妙2 分钟前
python打卡day59
开发语言·python
wuxuanok8 分钟前
Web后端开发-请求响应
java·开发语言·笔记·学习
Sally璐璐28 分钟前
IPSAN 共享存储详解:架构、优化与落地实践指南
开发语言·php
像风一样的男人@38 分钟前
python --货车装厢问题
开发语言·python
Humbunklung1 小时前
Rust枚举:让数据类型告别单调乏味
开发语言·后端·rust
蜡笔小电芯1 小时前
【C语言】指针与回调机制学习笔记
c语言·笔记·学习
Y1nhl1 小时前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展
OEC小胖胖1 小时前
深入理解 Vue.js 响应式原理及其在 Web 前端开发中的应用
开发语言·前端·javascript·vue.js·web
qq_401700411 小时前
C语言中位运算以及获取低8位和高8位、高低位合并
c语言·开发语言·算法
yanjiaweiya1 小时前
云原生-集群管理
java·开发语言·云原生