ArrayIndexOutOfBoundsException

看报错是数组越界了,发生在当程序中数组的下标超出数组的表示范围的时候

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

image.png
at line 5, Solution.twoSum 表示错在第五行
 Index 3 out of bounds for length 3  角标3超过了长度3
我们的输入是[3,2,4],在i=0的时候,当j=3,超过了数组的长度
哎, j <= nums.length - i 应该写为 j <= nums.length - 1    打错了字母搞的数组越界。。。。

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");
        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容