python3
正常方式:双重循环
6384 ms :Your runtime beats 7.14 % of python3 submissions
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
LEN = len(nums)
for i in range(LEN-1):
for j in range((i+1),LEN):
if (nums[i] + nums[j] == target):
return [i,j]
取位置 这个也不快只超过了23%
还有一个函数就是大家常用的enumerate 但是这个函数可以到20毫秒(社区里是这么写的)
class Solution:
def twoSum(self ,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
LEN = len(nums)
for i in range(LEN-1):
numsj= target - nums[i]
if numsj in nums[(i+1) :]:
return(i,nums[(i+1) :].index(numsj)+i+1)