LeetCode之Two Sum

霍金昨天回到了屬於他的宇宙星空,他本不屬於這裏,他屬於宇宙

前言,準備開始看LeetCode,不知道什麼時候能看完,但是有什麼關係呢?有時候做一些事,只是爲了興趣而已,何必要把自己搞的那麼辛苦,那麼信誓旦旦。

LeetCode官網:https://leetcode.com/

我是直接用GitHub授權登錄的。

問題

給定一個整數數組,返回這兩個數字的索引,使它們合計成一個特定的目標。

舉例

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 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");
}

時間複雜度:O(n^2)
空間複雜度:O(1)

解法二(雙向哈希表)

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

時間複雜度:O(n)
空間複雜度:O(n)

解法三(一次散列表)

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

時間複雜度:O(n)
空間複雜度:O(n)

借用知乎的一首打油詩

明有科舉八股,
今有leetcode。
leetcode定題目且重答案背誦。
美其名曰:”practice makes perfect.”
爲何今不如古?
非也非也,
科舉爲國取士,
leetcode爲Google篩碼工,
各取所需也。

發佈了46 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章