Description:
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.
Example:
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):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
return []
法二:Two-pass Hash
用一个字典存储元素的值和索引,遍历每个元素,查找对应补值是否存在,若存在且不是该元素本身则返回。
class Solution(object):
def twoSum(self, nums, target):
dic=dict()
for i in range(len(nums)):
dic[nums[i]]=i
for i in range(len(nums)):
other=target-nums[i]
if other in dic.keys() and dic[other]!=i:
return [i,dic[other]]
return []
法三:One-pass Hash
用一个字典存储元素的值和索引,遍历每个元素,若补码已经存在之前的字典中,则停止并返回,否认添加该元素至字典中。
注意这里补码的索引一定小于当前元素的索引,故放在前面且不需要判断二者是否相等。
class Solution(object):
def twoSum(self, nums, target):
dic=dict()
for i in range(len(nums)):
other=target-nums[i]
if other in dic.keys():
return [dic[other],i]
else:
dic[nums[i]]=i
return []