Bruteforce算法
双循环一个个检测所有两个数字组合
时间复杂度: O(n^2)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
for i in range(0, len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
result = [i, j]
break
return result
使用字典的算法
for 循环用字典存与当前数字的和为target的数字, 且如果在接下来的循环中有这个数字出现则代表有两个数字和为target
时间复杂度: O(n)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i in range(0, len(nums)):
if nums[i] in dic:
return [dic[nums[i]], i]
else:
dic[target-nums[i]] = i