力扣第一題,兩數之和

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int temp;
        int arr = new int[2];
        for(int i = 0; i < nums.length;i++){
            for(int j = i+1;j < nums.length-i-1;j++){
                temp = nums[i]+nums[j];
                if(target == temp){
                    // System.out.println("["+i+","+j+"]");
                    arr[i] = i;
                    arr[j] = j;
                }
            }
        }
        return arr;
    }
}

上面就是我的代碼,執行成功,我以爲自己解決了,於是提交了,結果系統給我的多餘一種結果的數組,系統報錯,我的arr數組超出容量。

當我把數組的容量改爲4,系統出現一個巨長的測試數組

[230,863,916,585,981,404,316,785,88,12,70,435,384,778,887,755,740,337,86,92,325,422,815,650,920,125,277,336,221,847,168,23,677,61,400,136,874,363,394,199,863,997,794,587,124,321,212,957,764,173,314,422,927,783,930,282,306,506,44,926,691,568,68,730,933,737,531,180,414,751,28,546,60,371,493,370,527,387,43,541,13,457,328,227,652,365,430,803,59,858,538,427,583,368,375,173,809,896,370,789] 

??這是想弄死我的arr數組嗎???

偷偷的看了一下官方的代碼

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

我的代碼很弱!

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