问题描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
例子
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
暴力求解
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
tmp = target - nums[i]
#print(tmp)
for j in range(i+1,len(nums)):
if tmp == nums[j]:
#print(i,j)
return i,j
s = Solution()
nums = [2,7,11,15]
# nums =[3,2,4]
target= 13
s.twoSum(nums,target)
效率分析
Runtime: 3296 ms, faster than 29.56% of Python online submissions for Two Sum.
Memory Usage: 12.5 MB, less than 81.85% of Python online submissions for Two Sum.
哈希表
dict = {nums[i]:i for i in range(len(nums))}#注意到这里将原本的值作为键了,0、1、2、3作为
# dict = {i:nums[i] for i in range(length)}
for i in range(len(nums)):
tmp = target - nums[i]
j = dict.get(tmp)#根据keys找values
if j!= None and j!=i:
print(i,j)
return i,j
效率分析
Runtime: 32 ms, faster than 82.89% of Python online submissions for Two Sum.
Memory Usage: 13.3 MB, less than 13.56% of Python online submissions for Two Sum.
final
for i in range(len(nums)):
tmp = target - nums.pop(0)
if tmp in nums:
return [i,nums.index(tmp)+i+1]
效率分析
Runtime: 776 ms, faster than 39.69% of Python online submissions for Two Sum.
Memory Usage: 12.6 MB, less than 77.88% of Python online submissions for Two Sum.
2019_6_2
keys = {}
for i in range(len(nums)):
if target-nums[i] in keys:
return [keys[target-nums[i]],i]
if nums[i] not in keys:
keys[nums[i]] = i
Runtime: 36 ms, faster than 80.16% of Python online submissions for Two Sum.
Memory Usage: 13 MB, less than 55.66% of Python online submissions for Two Sum.