gpt4 book ai didi

php - 这个解决方案有什么问题? (Perm-Missing-Elem codility test)

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:54:59 26 4
gpt4 key购买 nike

我已经开始玩 codility 并遇到了这个问题:

A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.

Your goal is to find that missing element.

Write a function:

int solution(int A[], int N); 

that, given a zero-indexed array A, returns the value of the missing element.

For example, given array A such that:

A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5

the function should return 4, as it is the missing element.

Assume that:

    N is an integer within the range [0..100,000];
the elements of A are all distinct;
each element of array A is an integer within the range [1..(N + 1)].

Complexity:

    expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).

我已经提交了以下解决方案(用 PHP):

function solution($A) {
$nr = count($A);
$totalSum = (($nr+1)*($nr+2))/2;
$arrSum = array_sum($A);
return ($totalSum-$arrSum);
}

它给了我 66 分(满分 100 分),因为它没有通过涉及大型数组的测试:“large_range 范围序列,长度 = ~100,000”结果:运行时错误测试程序意外终止标准输出:无效的结果类型,预期为 int。

我在本地测试了一个包含 100.000 个元素的数组,它没有任何问题。那么,我的代码似乎有什么问题,codility 使用了什么样的测试用例来返回“无效的结果类型,int expected”?

最佳答案

PermMissingElem 的 100/100 php 解决方案:

function solution($A) {   
$N = count($A);
$sum = ($N + 2) * ($N + 1) / 2;
for($i = 0; $i < $N; $i++){
$sum -= $A[$i];
}
return intval($sum);
}

关于php - 这个解决方案有什么问题? (Perm-Missing-Elem codility test),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19793045/

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