【发布时间】:2013-11-05 15:50:45
【问题描述】:
我开始玩 codility 并遇到了这个问题:
给出了一个由 N 个不同整数组成的零索引数组 A。 该数组包含 [1..(N + 1)] 范围内的整数,这意味着 恰好缺少一个元素。
你的目标是找到那个缺失的元素。
写一个函数:
int solution(int A[], int N);给定一个零索引数组 A,返回缺失的值 元素。
例如,给定数组 A 使得:
A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5
函数应该返回 4,因为它是缺少的元素。
假设:
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)].复杂性:
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”?
【问题讨论】:
-
这也不仅仅是元素个数的问题,也是一个数据类型所能容纳的最大值。如果将两个大
ints 相乘,则结果可能不适合int。这就是你在 IMO 中遇到的问题 -
@warunsl 你是对的。在做了更多研究之后,php int 类型取决于所使用的系统(在 32 位系统上可以保存高达 2147483647 的值,在 64 位系统上可以保存高达 9223372036854775807 的值)。超出此限制的任何内容都将自动转换为浮点数。我在 64 位系统上进行测试,这就是 ($nr+1)*($nr+2) 没有达到该限制的原因,但在代码方面它被转换为浮点数,使所有其他操作返回浮点类型。解决方案是在 return (int)($totalSum-$arrSum) 时添加类型转换。