要求:
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.
deftwoSum(nums, target):"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""'''
Time Limit Exceeded
'''
index = []
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
index.append(i)
index.append(j)
return index
deftwoSum(nums, target):"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
temp_num = nums[:] # [:]表示深拷贝,a = b 表示浅拷贝
temp_num.sort() # sort会改变原来数组,所以上面要深复制
i = 0
j = len(temp_num) - 1
index = []
while i < j:
if temp_num[i] + temp_num[j] == target:
for n in range(0,len(nums)):
if temp_num[i] == nums[n]:
index.append(n)
breakfor m in range(len(nums)-1,-1,-1):
if temp_num[j] == nums[m]:
index.append(m)
break
index.sort()
breakelif temp_num[i] + temp_num[j] > target:
j -= 1elif temp_num[i] + temp_num[j] < target:
i += 1return index
1.3 哈希法
解题思路:第2种方法写的太麻烦了,可以使用使用python中dict,也就是hashmap。
时间复杂度:O(n)
运行结果:耗时53ms
deftwoSum(nums, target):"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
index = 0for i in range(len(nums)):
if target - nums[i] in dict:
return [dict[target - nums[i]],i]
else:
dict[nums[i]] = index
index += 1