題目:https://leetcode-cn.com/problems/two-sum/description/
給定一個整數數組和一個目標值,找出數組中和為目標值的兩個數。
你可以假設每個輸入只對應一種答案,且同樣的元素不能被重復利用。
示例:
給定 nums = [2, 7, 11, 15], target = 9 因為 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
解法一
求差值,判斷差值是否在nums數組里
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ n = len(nums) for x in range(n): b = target-nums[x] if b in nums: y = nums.index(b) if y!=x: return x,y
時間復雜度:O(n2),空間復雜度:O(1) (補充:python中list對象的存儲結構采用的是線性表,因此其查詢復雜度為O(n) 也就是 if b in nums 時間復雜度是O(n))
解法二
求差值、把差值存進字典里作為鍵、索引作為值,第一次循環理解:d[7]=0 即字典d={7:0},表示為索引0需要數組里值為7的元素配對。 if 判斷是否為前面元素所需要配對的值 , 是則返回兩個索引值。(補充:nums[x] in d 是判斷值是否在字典某個key里面)
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ n = len(nums) #創建一個空字典 d = {} for x in range(n): a = target - nums[x] #字典d中存在nums[x]時 if nums[x] in d: return d[nums[x]],x #否則往字典增加鍵/值對 else: d[a] = x #邊往字典增加鍵/值對,邊與nums[x]進行對比
時間復雜度:O(1) 、空間復雜度O(n) (補充:dict對象的存儲結構采用的是散列表(hash表),其在最優情況下查詢復雜度為O(1))
解法三
暴力循環、不多說
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ #用len()方法取得nums列表的長度 n = len(nums) #x取值從0一直到n(不包括n) for x in range(n): #y取值從x+1一直到n(不包括n) #用x+1是減少不必要的循環,y的取值肯定是比x大 for y in range(x+1,n): #假如 target-nums[x]的某個值存在於nums中 if nums[y] == target - nums[x]: #返回x和y return x,y
時間復雜度:O(n2)、空間復雜度:O(1)
執行時間明顯多於一和二。
性能:解法二>解法一>解法三 。(補充:不能根據這個圖片的執行用時比較,應該從時間復雜度比較)