在編寫leecode上的算法第一題“兩數之和”時,遇到了一些問題,如下:
1.參數丟失
>>>Solution.twosum([2,3,4,5],8)
TypeError: twosum() missing 1 required positional argument: 'target'
原因:沒有創建對象
解決:
>>>a = Solution() #括號很重要
>>>a.twosum([2,3,4,5],8)
2.超出時間顯示
原因:時間複雜度高 O(n2)
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
i = 0
n = len(nums)
while i < n:
j = i+1
while j <n:
if nums[i] + nums[j] == target:
return [i,j]
j += 1
i += 1
解決: 降低時間複雜度,O(n)
class Solution:
def twoSum(self,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#用len()方法取得nums列表長度
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]進行對比