LeetCode 1. 兩數之和 (Python)
阿新 • • 發佈:2018-12-14
- 題目:
給定一個整數陣列 nums 和一個目標值 target,請你在該陣列中找出和為目標值的那 兩個 整數,並返回他們的陣列下標。
你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個陣列中同樣的元素。
- 示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
- 刷題筆記
思路一:
首先是第一次做題,沒有奇技淫巧,當時直接用暴力破解法
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for each in range(0,len(nums)-1): for each2 in range(each+1,len(nums)): if nums[each]+nums[each2]==target: return each,each2
在測試的時候通過,但是提交時超出時間限制而不通過,顯然這種方法效率不行。故舍之
(在C語言中暴力破解法效率高,能通過)
思路二:
通過字典方法查詢鍵值。
因為當列表為空時巢狀的for沒有找到數值。所以d[i] = item這句應該放在巢狀for後面
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ d = {} for i, item in enumerate(nums): temp = target - item for key,value in d.items(): if temp == value: return key,i d[i] = item return None
編譯通過!執行用時 2084 ms
思路三:
通過python自帶的列表尋找位置函式 index() 解題
注意 index() 沒有找到數值時會出錯。
index()方法語法:
str.index(str, beg=0, end=len(string))
程式碼:
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): temp = target - nums[i] try: i2 = nums.index(temp,i) if i!=i2: return i,i2 except: pass return None
編譯通過,用時1468 ms。