两数之和(C语言实现)

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

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

示例:
给定nums = [2, 7, 11, 15]; target = 9;

因为nums[0] + nums[1] = 2 + 7 = 9;
所以返回[0 ,1]

 

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

#define null 0

struct object
{
    int iValue;
    int iIndex;
};

int compare(const void *a, const void *b)
{
    return ((struct object*)a)->iValue - ((struct object*)b)->iValue;
}

static int *TwoSum(int *pInt, int iSize, int iTarget)
{
    int i;
    int j;
    int diff;
    int *result = null;
    struct object *pstObject = null;

    pstObject = (struct object *)malloc(iSize * sizeof(*pstObject));
    if (null == pstObject)
    {
        printf("\r\np1 malloc failed.");
        return null;
    }
    memset(pstObject, 0, iSize * sizeof(*pstObject));

    for (i = 0; i < iSize; i++)
    {
        pstObject[i].iValue = pInt[i];
        pstObject[i].iIndex = i;
    }

    qsort(pstObject, iSize, sizeof(*pstObject), compare);

    result = (int *)malloc(2 * sizeof(*result));
    if (null == result)
    {
        printf("\r\np2 malloc failed");
        return null;
    }
    memset(result, 0, 2 * sizeof(*result));


    i = 0;
    j = iSize - 1;
    while(i < j)
    {
        diff = iTarget - pstObject[i].iValue;

        if (diff > pstObject[j].iValue)
        {
            while ((++i<j) && (pstObject[i].iValue == pstObject[i - 1].iValue))
            {

            }
        }
        else if (diff < pstObject[j].iValue)
        {
            while ((i < --j) && (pstObject[j].iValue == pstObject[j + 1].iValue))
            {

            }
        }
        else
        {
            result[0] = pstObject[i].iIndex;
            result[1] = pstObject[j].iIndex;

            j = 0;
        }
    }

    free(pstObject);
    pstObject = null;

    return result;
}

int main()
{
    int aiArray[] = {3, 6, 9, 5, 2};
    //int iTarget = 5;
    int iTarget = 10;
    int iSize;
    int *result;

    iSize = sizeof(aiArray) / sizeof(*aiArray);

    result = TwoSum(aiArray, iSize, iTarget);
    if (null == result)
    {
        printf("\r\ntwo sum malloc failed");
    }
    else
    {
        printf("\r\nresult = [%d, %d]", result[0], result[1]);
    }

    free(result);
    result = null;

    return 0;
}

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值