题目描述:
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路 1:
直接暴力求解法,一个一个读取元素,判断求和是否等于target,返回两个元素的位置。这种算法的时间复杂度是O(n^2)。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if nums == []:
return None
else:
for i in range(len(nums)):
for j in range(len(nums)-i-1):
j=j+i+1
if nums[i]+nums[j]==target:
return [i,j]
解题思路 2 :
用字典进行求解,可以有效地降低复杂度,时间复杂度是O(n)。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for i, item in enumerate(nums):
temp = target-item
for key, value in dict.items():
if temp == value:
return [key,i]
dict[i]=item