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這個工具類。

 

 

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