解法一(7280 ms):
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
L = []
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
L.append(i)
L.append(j)
return L
解法二(896 ms ):
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
if target-nums[i] in nums:
idx=nums.index(target-nums[i])
if idx!=i:
return [i,idx]
解法三(36ms):
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic={}
for i in range(len(nums)):
var=target-nums[i]
if nums[i] in dic:
return [dic[nums[i]],i]
else:
dic[var] = i