2 qq 31933059 qq_31933059 于 2016.01.22 01:13 提问

求大神帮忙 C语言 LeetCode的 Two Sum问题

求大神帮忙。我run时显示Runtime Error,不知道问题在哪里。。
还有,我也不理解注释中的: * Note: The returned array must be malloced, assume caller calls free(). 这句是什么意思

题目:
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Subscribe to see which companies asked this question

我的代码:
/**

  • Note: The returned array must be malloced, assume caller calls free(). / int twoSum(int* nums, int numsSize, int target) { int i,j; int index1,index2; for(i=0;i<numsSize;i++) { for(j=0;j<numsSize;j++) { if(nums[i]!=0 && nums[j]!=0) { if(nums[i]+nums[j]==target) { if(nums[i]<=nums[j]) { index1=i+1; index2=j+1; } else { index1=j+1; index2=i+1; } } } } } printf("[%d,%d]",index1,index2); }

2个回答

caozhy
caozhy   Ds   Rxr 2016.01.22 02:57
已采纳
 int* twoSum(int* nums, int numsSize, int target) {
    int i,j;
    int index1,index2;
    for(i=0;i<numsSize;i++)
    {
        for(j=0;j<numsSize;j++)
        {
            if(nums[i]!=0 && nums[j]!=0)
            {
                if(nums[i]+nums[j]==target)
                {
                    if(nums[i]<=nums[j])
                    {
                        index1=i+1;
                        index2=j+1;
                    }
                    else
                    {
                        index1=j+1;
                        index2=i+1;
                    }
                }
            }
        }
    }
    printf("[%d,%d]",index1,index2);
    int * arr = (int *)malloc(sizeof(int) * 2);
    arr[0] = index1;
    arr[1] = index2;
    return arr;
}

int main()
{
    int nums[] = {2,7,11,15};
    int *p  = twoSum(nums, 4, 9);
    free(p);
}

如果你的程序没有别的错,它和它的调用者应该是这样的

xpqhqy1314
xpqhqy1314 没明白为什么要比较num[i]和num[j]的大小来确定index啊,求解释
大约一年之前 回复
qq_31933059
qq_31933059 通过了,非常感谢
接近 2 年之前 回复
caozhy
caozhy   Ds   Rxr 2016.01.22 02:50

Note: The returned array must be malloced, assume caller calls free().
返回的数组必须被分配,假设调用者负责释放

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!