Leet Code_python 1.two sum
自写代码:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in nums://可以直接用for循环去遍历nums列表中的数,找到需要的数
start_index = nums.index(i)//可以用index(i)检索列表中某数的位置,注意是英文括号()
next_index = start_index + 1
nums2 = nums[next_index: ]//可通过:列表【索引位置:空格】来对一个列表进行从索引位置到最后的切割
for j in nums2:
if j+i == target:
return(nums.index(i),nums2.index(j)+next_index)
思想:要找两个数的和,所以要遍历两次。
首先,从nums中从头到尾遍历所有数,找到第一个数
其次,把此第一个数后面的所有数组成新的列表(列表的切割)
其次,对新的列表再遍历
最后,用if语句判断两个列表中是否有相加等于target的数,如果有则直接返回,两个数在最初列表的位置。
错误:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in nums:
start_index = nums.index(i)
next_index = start_index + 1
nums2 = nums[next_index: ]
for j in nums2:
if j+i == target:
return(nums.index(i),nums.index(j))//*****
如果最后用的是nums.index(j)而不是nums2.index(j)+next_index,那么如果列表中有相同的数,就可能输出相同索引
说明:如果最后用的是nums.index(j)而不是nums2.index(j)+next_index,那么如果列表中有相同的数,就可能输出相同索引值。
eg:
输入:[3,3] 6
输出:[0,0]
本应是[0,1]的