題目描述:數組
Given an array of integers, return indices of the two numbers such that they add up to a specific target.微信
You may assume that each input would have exactly one solution, and you may not use the same element twice.測試
給定一個整數數組nums和一個目標值target,請你在該數組中找出和爲目標值的那兩個整數,並返回他們的數組下標。spa
你能夠假設每種輸入只會對應一個答案。可是你不能重複利用這個數組中一樣的元素。code
示例:blog
1 給定 nums = [2, 7, 11, 15], target = 9 2 3 由於 nums[0] + nums[1] = 2 + 7 = 9 4 因此返回 [0, 1] 5 6 來源:力扣(LeetCode)
本題的難度在力扣中顯示爲簡單,其自己也的確不難。拿到題後的第一個想法就是瘋狂遍歷,一定有列表中的兩數之和與目標值相等,兩數相加也就須要兩層循環而已。索引
1 for i in range(len(nums)): 2 for j in range(i+1, len(nums)): 3 if nums[i] + nums[j] == target: 4 return list([i, j])
顯然本題的數據量不多,感受不到慢多少,可是若是利用time庫計算下其計算時間,該方案並非最佳的。這時候就能夠體會到Python的強大之處了。Python中有不少出人意料的語法,就像(A)in(B)表示(A)在(B)中這樣的,簡直和咱們生活中說話同樣,爲了下降複雜度,我就開始想着減小一層循環。看一下下面這段程序:ci
1 class Solution: 2 def twoSum(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 for i in nums: 9 n = target - i 10 if n in nums and nums.index(n) != nums.index(i): 11 return [nums.index(i),nums.index(n)]
是否是僅用一層循環就解決問題了呢。的確複雜度是降下來了,可是當我提交的時候出問題了。再看一遍程序發現,這裏沒有判斷兩個數相等的狀況。Python中有一個數據類型是字典,也就是經過索引來定位數據。同時字典也有不少它自身的屬性和方法,能夠和方便的找到內容所對應的索引。對上面的錯誤進行了改進以後爲:element
1 class Solution: 2 def twoSum(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 dic1 = {nums[i]:i for i in range(len(nums))} 9 dic2 = {i:target-nums[i] for i in range(len(nums))} 10 for i in range(len(nums)): 11 j = dic1.get(dic2.get(i)) 12 if j and j != i: 13 return [i,j]