題目在leetcode上的鏈接爲:
https://leetcode-cn.com/problems/two-sum/
題目描述
解題思路
使用dict來做
1.將列表nums中的元素值作爲key,元素對應下標作爲value,建立dict
2.遍歷列表nums元素a,判斷b = target-a是否在dict中,如果b在dict中且a,b的下標不同,輸出a,b下標
在建立dict時可能會出現nums中的元素相同而鍵值覆蓋的情況,但是由於第二次遍歷列表nums時,nums中的元素和以前一致,所以鍵值覆蓋的情況並不會產生影響。
下面看一個具體的測試用例:
num3 = [3, 3] target = 9
1.建立dict時,由於3出現了兩次,所以建立的dict = {3 : 1}
2.當我們遍歷nums時,當遍歷到第一個元素nums[0] = 3(把nums[0]看做a)時,我們判斷 b = target - nums[0] = 3在dict中,而且a的下標爲0,b的下標爲1,符合條件,因此可輸出[0, 1]得到正確答案。
複雜度分析:
時間複雜度爲o(n),需要串行地兩次遍歷整個數組
空間複雜度爲o(n),需要使用dict來存放數組中元素與索引的映射
python代碼:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
result = []
for i in range(len(nums)):
d[nums[i]] = i
for i in range(len(nums)):
b = target - nums[i]
if b in d and d[b] != i:
result.append(i)
result.append(d[b])
return result