千家信息网

如何编写代码实现两数之和

发表于:2025-02-11 作者:千家信息网编辑
千家信息网最后更新 2025年02月11日,本篇内容主要讲解"如何编写代码实现两数之和",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"如何编写代码实现两数之和"吧!一、说明给定一个整数数组和一个目标值
千家信息网最后更新 2025年02月11日如何编写代码实现两数之和

本篇内容主要讲解"如何编写代码实现两数之和",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"如何编写代码实现两数之和"吧!

一、说明

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15] , target = 9 。

因为 nums[0] + nums[1] = 2 + 7 = 9 ,

所以返回 [0, 1]

二、解决方案参考

1. Swift 语言

2. JavaScript 语言

3. Python 语言

4. Java 语言

5. C++ 语言

6. C 语言

#include #include struct object {    int val;    int index;};static int compare(const void *a, const void *b){    return ((struct object *) a)->val - ((struct object *) b)->val;}static int * twosum(int *nums, int numsSize, int target){    int i, j;    struct object *objs = malloc(numsSize * sizeof(*objs));    for (i = 0; i < numsSize; i++) {        objs[i].val = nums[i];        objs[i].index = i;    }    qsort(objs, numsSize, sizeof(*objs), compare);        int count = 0;    int *results = malloc(2 * sizeof(int));    i = 0;    j = numsSize - 1;    while (i < j) {        int diff = target - objs[i].val;        if (diff > objs[j].val) {            while (++i < j && objs[i].val == objs[i - 1].val) {}        } else if (diff < objs[j].val) {            while (--j > i && objs[j].val == objs[j + 1].val) {}        } else {            results[0] = objs[i].index;            results[1] = objs[j].index;            return results;        }    }    return NULL;}int main(void){    //int nums[] = {-1, -2, -3, -4, -5};    //int target = -8;    //int nums[] = {0,4,3,0};    //int target = 0;    int nums[] = { 3, 2, 3 };    int count = sizeof(nums) / sizeof(*nums);    int target = 6;    int *indexes = twosum(nums, count, target);    if (indexes != NULL) {        printf("%d %d", indexes[0], indexes[1]);    } else {        printf("Not found");    }    return 0;}

到此,相信大家对"如何编写代码实现两数之和"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0