一、题目要求
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
二、代码
1.第一次的代码是使用先复制整个nums的方法,每寻找一次复制一次
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for num in nums:
nums_copy=nums[:]
pos1=nums_copy.index(num)
nums_copy.remove(num)
if target-num in nums_copy:
result=[pos1,nums_copy.index(target-num)+1]
return result
2.代码思路时,每用nums的一个数字去寻找与他加起来能等于target的数字时,首先记录,删除然后记录一个索引不断累加,代码简洁了很多
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
i=0
while True:
a=nums[0]
nums.remove(a)
if target-a in nums:
result=[i,nums.index(target-a)+i+1]
return result
i += 1
三、结果
1.效果并不好
2.代码效果略有提升