给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 index[0, 1]
def twoSum(nums, target): l = [] # 外部栈存储 s = 0 # 外部循环次数 for _ in nums: i = 0 s = s + 1 p = nums.pop(0) l.append(p) for v in nums: if v == target - p: return [len(l) - 1, s + i] i = i + 1
我的想法,是取出1个元素放入外部栈,并记录其值,然后在剩下的列表中遍历满足条件的元素.s
,i
,为了标记满足要求的元素的序号作用.
验证过程中发现,每当我输入
print(twoSum([1,3,3,5,2],7))
调试结果就会显示None
,具体就是当满足的两个数都在输入列表末尾,就会出现None
.
python新手,请多指教.
收到一只叮咚
相关分类