數組中兩數相加

數組中兩數相加

如題:

假設數組int[] array = {2, 7, 11, 15},target = 9,找出數組中是否存在array[i] + array[j] = target,i不等於j,如果有,返回[i, j],沒有則返回0。

這道題題目雖短,但卻很經典,最簡單的思路就是兩層for循環進行數組的遍歷,把數組中元素相加和target對比。

解法一: 代碼如下

public class SumTwo {

    private static int[] sumTwoNum(int[] array, int target) {
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] + array[j] == target) {
                    return new int[]{i, j};
                }
            }
        }

        return null;
    }

    public static void main(String[] args) {
        int[] array = {2, 7, 11, 15};
        int target = 10;

        System.out.println(Arrays.toString(sumTwoNum(array, target)));
    }
}

上面方法很基礎,但是需要兩層循環,那有沒有一層循環就能解決的呢?答案是肯定的。要一層循環就解決這個問題,那麼肯定需要把其中一個數存起來,等待另一個數與它相加等於target。

解法二:

public class SumTwo {

    private static int[] sumTwoNum2(int[] array, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
            Integer integer = map.get(array[i]);
            if (null != integer) {
                return new int[]{integer, i};
            }
            map.put(target - array[i], i);
        }

        return null;
    }

    public static void main(String[] args) {
        int[] array = {2, 7, 11, 15};
        int target = 13;

        System.out.println(Arrays.toString(sumTwoNum2(array, target)));
    }
}

第二種解法的思想就是把array[i]需要的另一個數target - array[i]作爲map的鍵,array[i]的下標i作爲值存起來,如果數組中有值和map的鍵相等,即匹配成功。

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