看報(bào)錯(cuò)是數(shù)組越界了,發(fā)生在當(dāng)程序中數(shù)組的下標(biāo)超出數(shù)組的表示范圍的時(shí)候
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at line 5, Solution.twoSum
at line 54, DriverSolution.helper
at line 87, Driver.main
at line 5, Solution.twoSum 表示錯(cuò)在第五行
Index 3 out of bounds for length 3 角標(biāo)3超過了長度3
我們的輸入是[3,2,4],在i=0的時(shí)候倍奢,當(dāng)j=3环揽,超過了數(shù)組的長度
哎坤候, j <= nums.length - i 應(yīng)該寫為 j <= nums.length - 1 打錯(cuò)了字母搞的數(shù)組越界。务唐。。带兜。
class Solution {
public int[] twoSum(int[] nums, int target) {
for( int i = 0;i <= nums.length-1; i++){
for( int j = i + 1; j <= nums.length - i ; j++){
if( target == nums[i] + nums[j]) {
return new int[]{i,j};
}
}
}
throw new IllegalArgumentException("no two sum solution");
}
}