Solution问题
问题描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解法一:暴力
时间复杂度:O(n^2)
def twoSum1(self, nums, target):
"""
暴力
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i]+nums[j]==target:
return i,j
else:
continue
解法二:巧用差值
时间复杂度O(n)
def twoSum2(self, nums, target):
'''
差值
:param list nums:
:param int target:
:return int x,int y:
'''
for x in range(len(nums)):
a=target-nums[x]
if a in nums:
y=nums.index(a)
if x==y:
continue
else:
return x,y
else:
continue
解法三:字典解决问题
时间复杂度O(n)
def twoSum3(self, nums, target):
'''
字典解决问题
:param dictory nums:
:param int target:
:return int x, int y:
'''
hashmap = {
}
for ind, num in enumerate(nums):
hashmap[num] = ind
for i, num in enumerate(nums):
j = hashmap.get(target - num)
if j is not None and i != j:
return [i, j]
解法四:字典解决问题(方法三优化版本)
时间复杂度
def twoSum(self,nums, target):
'''
字典解决问题
:param dictory nums:
:param int target:
:return int x, int y:
'''
hashmap = {
}
for i, num in enumerate(nums):
if hashmap.get(target - num) is not None:
return [i, hashmap.get(target - num)]
hashmap[num] = i