【发布时间】:2021-09-13 00:07:09
【问题描述】:
编辑:由斯蒂芬解决 但是:现在,剩下的唯一问题是:为什么较短的解决方案性能如此差(结果:100%,性能:32%,结果:66%),而较长的版本性能更好但似乎产生更差的结果(60%、50%、55%)?
原始问题的开始: 我目前正在尝试 Codility 演示测试,要解决的问题是找到不包含在给定数组中的 0 以上的最小整数。 这是我在两个不同版本中的代码,结果相同。输出是正确的,但编译器抛出上述错误,导致测试失败。当在 SO 上查找此错误时,这似乎是 Codility 上的常见错误。
# you can write to stdout for debugging purposes, e.g.
# puts "this is a debug message"
def solution(a)
# write your code in Ruby 2.2
num = 1
a=a.sort
a.uniq!
a.each do |x|
if x == num then
num += 1
next
else
break
end
end
puts num
end
或
def solution(a)
# write your code in Ruby 2.2
num = 1
while a.include?(num) do
num += 1
end
puts num
end
结果:
Compilation successful.
Example test: [1, 3, 6, 4, 1, 2]
Output (stderr):
Invalid result type, Integer expected, NilClass found
Output:
5
RUNTIME ERROR (tested program terminated with exit code 1)
Example test: [1, 2, 3]
Output (stderr):
Invalid result type, Integer expected, NilClass found
Output:
4
RUNTIME ERROR (tested program terminated with exit code 1)
Example test: [-1, -3]
Output (stderr):
Invalid result type, Integer expected, NilClass found
Output:
1
RUNTIME ERROR (tested program terminated with exit code 1)
Producing output might cause your solution to fail performance tests.
You should remove code that produces output before you submit your solution.
Detected some errors.
我真的不明白出了什么问题。数组只包含整数,num 是整数,一切都是整数,但编译器说它是 NIL。我能做什么?
编辑:相同的代码在 SoloLearn 应用程序和我的本地机器上运行没有错误。
【问题讨论】:
-
puts的返回值为nil。您的方法可能应该返回结果而不是打印它。 -
是的,这就是解决方案。谢谢!
标签: ruby null integer runtime-error