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

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

成都创新互联是工信部颁发资质IDC服务器商,为用户提供优质的雅安服务器托管服务

一、说明

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

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

        示例:

                给定 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;
}

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


本文标题:如何编写代码实现两数之和
网站路径:http://bzwzjz.com/article/pijcse.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 成都营销网站建设 温江网站设计 成都网站制作 手机网站制作设计 成都定制网站建设 网站制作报价 广安网站设计 成都网站制作 重庆网站建设 成都商城网站制作 移动网站建设 高端网站设计 成都网站设计 成都网站建设 公司网站建设 响应式网站建设 重庆手机网站建设 盐亭网站设计 高端品牌网站建设 成都营销网站制作 成都网站建设流程 成都网站设计制作公司