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

LeetCode两数之和问题:为何twoSum函数返回数组始终为空?

问题排查与修复:LeetCode twoSum 返回空数组的原因

你的代码逻辑本身是对的,但忽略了LeetCode题目要求里的一个关键细节:必须通过returnSize参数告诉调用者返回数组的长度。

核心问题

LeetCode的判题系统依赖returnSize的值来确定要读取返回数组的元素数量。你的原代码中从未对*returnSize赋值,这会导致未定义行为——判题系统可能读取到一个随机的初始值(比如0),因此即使你malloc了正确的数组并填充了下标,系统也会认为你返回的是空数组。

修复后的代码

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    int* arrInd = (int *)malloc(2 * sizeof(int));
    // 初始化returnSize为0,避免未定义行为
    *returnSize = 0;
    for (int i = 0; i < numsSize; i++) {
        for (int counter = i + 1; counter < numsSize; counter++) {
            if (nums[i] + nums[counter] == target) {
                arrInd[0] = i;
                arrInd[1] = counter;
                // 关键:告知调用者返回数组有2个元素
                *returnSize = 2;
                return arrInd;
            }
        }
    }
    // 未找到结果时,释放已申请的内存避免泄漏
    free(arrInd);
    return NULL;
}

修复点说明

  1. 初始化returnSize:函数开头先把*returnSize设为0,避免后续未找到结果时参数处于未初始化状态。
  2. 找到结果时设置returnSize:当找到符合条件的下标对后,必须将*returnSize赋值为2,让判题系统知道返回的数组包含2个元素。
  3. 内存泄漏修复:如果遍历完数组没找到结果,要释放之前malloc的内存,避免内存泄漏(虽然LeetCode判题可能不强制要求,但这是C语言编程的良好习惯)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:49:58