3.最终提交代码顺序遍历数组,每访问一个数,就用目标数减去这个数,查看减法的结果是否存在于数组中。为了避免返回的结果是自己和自己相加,首先将自己先移除,然后再判断。如果在的话,就输出两个数的下标;如果不在的话,就将刚才移掉的自己再插入到原来的位置上保持不变,访问下一个数。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
target1 = nums[i]
target2 = target-target1
nums.remove(target1)
if target2 in nums:
return [i,nums.index(target2)+1]
else:
nums.insert(i,target1)
4.编写验证过程中的完整代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
target1 = nums[i]
target2 = target-target1
nums.remove(target1)
if target2 in nums:
return [i,nums.index(target2)+1]
else:
nums.insert(i,target1)
solution = Solution()
print(solution.twoSum([2,7,11,15], 9))
拒绝内耗,永远心存善念。



