LeetCode-两数之和(Java)【解决错误过程&正解】

题目:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

运行下面的代码报错:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

public class TwoSum {
    public static int[] twoSum(int[] nums, int target) {
        int[] ints = new int[2];
        for (int i=0 ; i<=nums.length ; i++){
            if(nums[i] + nums[i+1] == target){
                ints[0] = i ;
                ints[1] = i+1;
            }
        }
        return ints;
    }

    public static void main(String[] args) {

        int[] arr = {2,7,11,15};
        int target = 9;

        twoSum(arr,target);
    }
}

错误导致的原因:当"i=nums.length"时,代码第5行中的“nums[i+1]”可能导致数组下标越界的异常 。

为了让“i+1”这个下标不越界,做出如下修改:

public class TwoSum {

    public static int[] twoSum(int[] nums, int target) {
        int[] ints = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    ints[0] = i;
                    ints[1] = j;
                    return ints;
                }
            }
        }
        throw new IllegalArgumentException("两数之和没有等于"+target);
    }

    public static void main(String[] args) {

        int[] arr = {2, 7, 11, 15};
        int target = 9;

        int[] ints = twoSum(arr, target);
        System.out.println(Arrays.toString(ints));
    }
}

这里还需要注意一点,代码倒数第一行的 System.out.println 默认调用的是对象的 toString() 方法,如果想要打印数组 inits 就需要使用 Arrays这个工具类。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章