給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。 數組
你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。函數
示例:code
給定 nums = [2, 7, 11, 15], target = 9內存
由於 nums[0] + nums[1] = 2 + 7 = 9
因此返回 [0, 1]get
方法1,暴力解法。it
直接每個元素都與本身以前的元素相加看是否有目標值,有就輸出。io
代碼以下:class
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ n = len(nums) for i in range(n): for j in range(i): if nums[i] + nums[j] == target: target_num = [i,j] return target_num return None
時間消耗和空間消耗以下:效率
執行用時: 4500 ms, 在Two Sum的Python3提交中擊敗了32.72% 的用戶List
內存消耗: 7.3 MB, 在Two Sum的Python3提交中擊敗了85.58% 的用戶
方法2,使用enumerate函數
查看評論使用enumerate 函數效率更高。
enumerate函數能夠將一個數組轉化爲一個key從開始,值爲數組對應元素的字典。
代碼以下:
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if not nums: return None d = dict() for i,item in enumerate(nums): tmp = target – item if tmp in d: return [i, d[tmp]] d[item] = i return None
時間消耗和空間消耗以下:
執行用時: 44 ms, 在Two Sum的Python3提交中擊敗了99.77% 的用戶
內存消耗: 7.9 MB, 在Two Sum的Python3提交中擊敗了46.97% 的用戶