I have tried two kinds of the algorithm.
Do sum by loop and check whether the sum is equal to the target
1
2
3
4
5for i in range(len(nums)):
sumList = [nums[i]+item for item in nums[i+1:]]
for sumNum in sumList:
if sumNum == target:
return [i, sumList.index(sumNum)+i+1]Use the
index()
in List
By using this, the performance become much better.1
2
3
4for i in range(len(nums)):
targetNum = target-nums[i]
if targetNum in nums and nums.index(targetNum) != i:
return i, nums.index(targetNum)