Leet Code_python 1.two sum

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]的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值