1. 程式人生 > >Java&LeetCode 初入門——001. 兩數之和

Java&LeetCode 初入門——001. 兩數之和

Java&LeetCode 初入門——001. 兩數之和


文內程式碼全部採用JAVA語言。

題目描述

給定一個整數陣列 nums 和一個目標值 target,請你在該陣列中找出和為目標值的那 兩個 整數,並返回他們的陣列下標。你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個陣列中同樣的元素。

測試用例

給定 nums = [2, 7, 11, 15], target = 9
因為 nums[
0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

官方解法

解法1——暴力法

暴力法,顧名思義,直接採用兩次迴圈,遍歷陣列中的所有可能,尋找合適的解。

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"); }

解法2——兩遍雜湊表

建立位置與數值的對應關係表,第一遍雜湊表將元素位置作為key建立雜湊表,第二遍查詢目標加數的位置,如果存在且不是被加數,那麼返回。最大計算次數從n2,變為2n。

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new
HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); }//將元素放進hash表中 for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { return new int[] { i, map.get(complement) }; } } throw new IllegalArgumentException("No two sum solution"); }

解法3——一遍雜湊表

邊放邊找,進一步降低複雜度。

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}