当前位置: 首页 > article >正文

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.代码实现 

#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;
}


http://www.kler.cn/a/459269.html

相关文章:

  • 大数据面试笔试宝典之HBase面试
  • ECMAScript基础
  • Cypress测试框架详解:轻松实现端到端自动化测试
  • 项目总结-ElasticSearch性能优化考虑点
  • 飞搭系列 | 移动端列表批量选择:让数据处理更便捷
  • Mac、Linux命令
  • Facebook数据分析和报告不准确该如何解决?
  • 2025常见的软件测试面试题
  • Flask 与 SocketIO 正确初始化及最佳实践调试
  • 解读目前AI就业岗位——大语言模型(LLM)应用工程师学习路线、就业前景及岗位全解析
  • 电脑缺失libcurl.dll怎么解决?详解电脑libcurl.dll文件丢失问题
  • Rocky9网络基本连接配置
  • SpringBoot开发——整合 Elasticsearch 实现数据高效搜索
  • 【数据结构】线性数据结构——队列
  • 如何用jmeter工具进行性能测试
  • .net core 的网络编程
  • 线性代数概念整理笔记
  • python去水印
  • HAL 库 HAL_UARTEx_ReceiveToIdle_IT 函数解析
  • 《深入挖掘Python加解密:自定义加密算法的设计与实现》