gpt4 book ai didi

C 代码审查 : Where is my mistake trying to solve this simple riddle?

转载 作者:行者123 更新时间:2023-11-30 15:14:57 25 4
gpt4 key购买 nike

我正在尝试用 C 语言解决一个简单的问题,如下所示:

Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1]. The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])| In other words, it is the absolute difference between the sum of the first part and the sum of the second part.

Also: N is an integer within the range [2..100,000]; each element of array A is an integer within the range [−1,000..1,000].

我想出了以下代码:

int solution(int A[], int N) {
// write your code in C99
double firstSum = A[0];
double secondSum = 0;

double curDiff, maxDiff, maxIndex = 1;

for(int i = 1; i < N; i++)
{
secondSum += A[i];
}

curDiff = abs(firstSum - secondSum);
maxDiff = curDiff;

for(int i = 2; i < N; i++)
{
secondSum -= A[i-1];
firstSum += A[i-1];
curDiff = abs(firstSum - secondSum);
if(curDiff > maxDiff)
maxIndex = i;
}
return maxIndex;
}

根据我进行此测试的网站,这确实很糟糕。该网站说代码未能通过他们运行的大部分测试,但我不明白为什么(他们不提供测试)。该代码对我来说似乎很好。此外,他们说解决方案是 O(n) 最坏情况空间复杂度(不包括输入),而我已经设法在 O(1) 内做到这一点,所以看起来有些不对劲。

最佳答案

您返回了错误的值。他们寻找的是最小差异,而不是寻找最小差异的P。您可以从here中选择一个解决方案或herehere以选择的语言。

关于C 代码审查 : Where is my mistake trying to solve this simple riddle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33809237/

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