我的代码应该找到字段中的最大值并返回数字的索引。如果它们是具有相同编号的索引,则应返回该对(或组)中较低的索引。但是,当我的所有数字均为负数时,我的代码不起作用。它始终返回 0,这是 bestIndex 的默认值。你能帮我修复我的代码吗?谢谢
这是我的代码:
int bestIndex = 0;
for (int i = 0; i < field.length; i++) {
bestIndex = field[i] > field[bestIndex] ? i : bestIndex;
}
return bestIndex;
最佳答案
在您的评论中您说:
[0,0,0,-5,-4,-2,-1]. I would want my code to return -1, but my code always returns 0
最后你揭示了你真正想要的东西。
您不需要数组中较大项的索引,而是较大项本身,仅在负项中!
但是您提供的代码返回较大项目的索引。
因此,更改为这个(我正在使用您的代码逻辑):
int greater = Integer.MIN_VALUE;
for (int i = 0; i < field.length; i++) {
if (field[i] < 0)
greater = field[i] > greater ? field[i] : greater;
}
return greater;
如果至少有 1 个负数,则返回较大的负数。
关于java - 字段中最大数字的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53584217/