You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode两数之和C语言实现返回空数组,是否与returnSize有关?

两数之和C语言实现返回空数组,问题出在returnSize参数吗?

我正在用C语言解决LeetCode的两数之和问题——要求返回数组中两个和为目标值的元素的索引,题目保证每组输入仅有唯一解。我已经用Python实现了该题,但C语言版本的程序却返回空数组。请问我遗漏了什么?是否与returnSize参数有关?

我尝试的解决方案如下:

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int* answer;
    answer = malloc(2*sizeof(int));

    // Success flag flips when two ints are identified
    bool success = false;

    // Look through every element of nums
    for(int first_number = 0; first_number < numsSize; first_number++)
    {
        // If index is at end of array, do not check further.
        if(first_number < numsSize)
        {
            // For each number in array, look at all of the numbers after it
            for(int second_number=(first_number + 1); second_number < numsSize; second_number++)
            {
                if((nums[first_number] + nums[second_number] == target))
                {
                    answer[0] = first_number;
                    answer[1] = second_number;
                    // Flip success flag
                    success = true;
                }
            }
        }

        // Check success flag and break. No need to check further.
        if(success){
            break;
        }
    }

    return answer;
}

问题已解决

感谢Fe2O3和WhozCraig的解释,问题确实出在returnSize参数上。int *returnSize是指向存储输出数组大小的变量的指针,C语言中动态分配的数组无法像静态数组(比如int arr[2])那样让调用方直接获取长度,必须通过这个指针主动设置输出数组的元素个数。

原代码完全没有对returnSize进行赋值,调用方(LeetCode判题系统)无法得知返回数组的长度,因此会判定返回的是空数组。

修正方法

因为题目保证有唯一解,只需要在找到结果后给returnSize指向的变量赋值为2即可,比如在设置success = true;的代码后添加:

*returnSize = 2;

或者直接在返回前统一设置(因为题目确保有解):

*returnSize = 2;
return answer;

另外,原代码中有一段冗余的判断if(first_number < numsSize)——外层循环的条件已经是first_number < numsSize,这个内部判断完全可以删除,不影响逻辑但能精简代码。

内容的提问来源于stack exchange,提问作者JDCirbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 07:15:39