1. 程式人生 > 實用技巧 >LeetCode刷題實戰1:兩數之和

LeetCode刷題實戰1:兩數之和

題目描述

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

示例

給定 nums = [2, 7, 11, 15], target = 9

因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解答

找兩個數和等於 target,第一反應就是暴力列舉。假設陣列長度為 n,那麼一個雙重迴圈就可以搞定。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        lens = len(nums)
        for i in range(lens-1):
            for j in range(i+1,lens):
                if nums[i] + nums[j] == target:
                    return [i, j]

這樣做當然是正確的,但顯然不是最好的答案。根據經驗,一般情況下 O(n^2) 的演算法都不是最優解。

引入 map

map 是一個非常常用的容器,用來儲存 key-value 格式的資料對。在這道題中,我們可以將元素和它在陣列當中對應的下標儲存進 map 中。也就是說我們把所有資料對應的下標儲存好了之後,我們在遍歷的時候,就可以去掉 j 那一重迴圈,而直接判斷 target-a[i] 在不在 map 中即可。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        lens = len(nums)
        for i in range(lens):
            a = target - nums[i]
            if a in nums:
                j = nums.index(a)
                if i == j:
                    continue
                else:
                    return [i, j]