上面return stones[0]错了,java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 at line 23, Solution.lastStoneWeight at line 54, __DriverSolution__.__helper__ at line 84, __Driver__.main
时间: 2024-04-08 13:34:38 浏览: 57
java 数组下标越界异常(ArrayIndexOutOfBoundsException)
4星 · 用户满意度95%
非常抱歉,我犯了一个错误。在修正后的代码中,应该在返回之前先检查是否还有剩余的石头。如果没有剩余的石头,应该返回0。修改后的代码如下:
```java
class Solution {
public int lastStoneWeight(int[] stones) {
while (stones.length > 1) {
for (int i = 0; i < stones.length; i++) {
for (int j = 1; j < stones.length; j++) {
if (stones[i] > stones[j]) {
int temp = stones[i];
stones[i] = stones[j];
stones[j] = temp;
}
}
}
if (stones[stones.length - 1] <= stones[stones.length - 2]) {
stones[stones.length - 2] -= stones[stones.length - 1];
stones = Arrays.copyOf(stones, stones.length - 1);
} else {
stones = Arrays.copyOf(stones, stones.length - 2);
}
}
if (stones.length == 0) {
return 0;
} else {
return stones[0];
}
}
}
```
这样应该就可以避免之前的数组越界错误了。请尝试运行修正后的代码,如果还有其他问题,请随时告诉我。
阅读全文