java - 使用 Java 编写代码中的 PassingCars 问题
问题描述
我正在做代码任务。我目前正在通过汽车任务 - https://app.codility.com/programmers/lessons/5-prefix_sums/passing_cars/;
其中一项性能测试,我得到“错误答案,得到 -1794967296 预期 -1”
(性能测试名称为“large_big_answer 0..01..1,长度 = ~100,000”)
其他测试做得很好
我想知道如何纠正这个错误
这是我的代码
class Solution {
public int solution(int[] A) {
int mul = 0;
int cnt = 0;
for(int i = 0 ; i<A.length ; i++){
if(A[i] == 0) mul++;
else cnt = cnt+mul;
}
if(cnt>1000000000) return -1;
return cnt;
}
}
解决方案
正如@Nicholas K 所指出的,这个问题确实与溢出有关。
将检查if (cnt > 1_000_000_000)
移到 for 循环中。要求是:
如果经过的汽车对数超过 1,000,000,000,则该函数应返回 -1。
因此,一旦对数超过计数,则停止。
所以,
public int solution(int[] A) {
int mul = 0;
int cnt = 0;
for(int i = 0 ; i<A.length ; i++){
if(A[i] == 0) mul++;
else cnt = cnt+mul;
if(cnt>1000000000) return -1;
}
return cnt;
}
这是一个显示失败的测试用例:
@Test
public void testHalfEach() {
final int[] inp = new int[100_000];
final int exp = -1;
Arrays.fill(inp, 0, 50_000, 0);
Arrays.fill(inp, 50_000, 100_000, 1);
validate(inp, exp);
}
private void validate(int[] inp, int exp)
{
PassingCars prog = new PassingCars();
int ans = prog.solution(inp);
assertEquals(exp, ans);
}
更改检查的位置将允许此测试通过。
推荐阅读
- html - 如何防止 ::after 元素将居中的文本从中心移开?
- c# - MVC 编辑和发送带有局部视图的模型视图
- php - 为什么 PHP 错误处理程序会乱序运行?
- python - 如何在 Python 的 for 循环中创建超时?
- r - 将表格 grob 居中对齐到 x 轴标签
- javascript - Flask 将 EventStreams 发送到 HTML 和 JS 获取事件消息
- bash - 如何将变量设置为 Bash 中两个命令的输出
- mongodb - 命令“mongod --auth --bind_ip_all”无限运行并消耗太多RAM - Mongo with Docker
- reactjs - 如何在 Apexchart 中自定义工具提示的标题和正文?
- python - Python3.8 `all()` 不短路