gpt4 book ai didi

c - 修复用于解决搜索范围的代码

转载 作者:行者123 更新时间:2023-11-30 19:05:26 25 4
gpt4 key购买 nike

以下代码针对 leetcode 问题 -- Search for a Range (请点击查看详情)。代码的运行时复杂度尚未优化,但预计不会出现一些 bug。你能帮我找出错误在哪里吗?代码及结果如下。

代码:

/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* searchRange(int* nums, int numsSize, int target, int* returnSize) {
int* a = malloc(sizeof(int) * (*returnSize));
a[0] = -1;
a[1] = -1;
int i;
for(i = 0; i < numsSize && a[0] == -1; i++){
if(nums[i] == target)
a[0] = i;
}
for(int j = i+1; j < numsSize; j++){
if(nums[j] == target)
a[1] = j;
}
return a;
}

运行代码结果:

您的输入

[5,7,7,8,8,10]
8

你的答案

[]

预期答案

[3,4]

最佳答案

您的代码可以使用 *returnSize 指向的变量值来解释错误行为。您的输出意味着该值为 0。
从名称和一般用途来看,您需要找到该变量的合适值,并在使用它之前通过指针 returnSize 写入它。
您正在使用它来将返回内存分配为 0 大小。这使得对 a 的任何 mmember 成员的任何访问都非常可疑,例如

a[0] = -1;
a[1] = -1;

事实上,您的输出有零个数字,这可能是一个循环(未显示),它只是简单地记录 returnSize == 0

我建议首先确定目标值和第一个索引出现的次数。
然后通过 *returnSize 写入该值。
然后是 malloc 和适当大小的数组。
然后用 first_index + counter 循环 0 到 size-1 填充数组。

关于c - 修复用于解决搜索范围的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49828326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com