Leetcode第一题------两数之和,第一次刷题的痛

Leetcode第一题,两数之和!!!
呜呜呜呜,万万没想到,被虐到不是因为题目本身,而是因为输出!!!在jupyter上运行出来,在leetcode上就是输出[]。崩溃
先贴一个别人的正确代码:

class Solution(object):
   def twoSum(self, nums, target):
       """
       :type nums: List[int]
       :type target: int
       :rtype: List[int]
       """
       for i, a in enumerate(nums):
           for j, b in enumerate(nums[i + 1 - len(nums):]):
               if a + b == target:
                   return [i, j + i + 1]
       return [-1, -1]

再贴一个我自己出来结果但是leetcode上运行不出来的代码:


nums = []
list = []
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(len(nums)-1):
                if nums[i] + nums[j] == target:
                    list.append((nums[i],nums[j]))
                    return list
                    break
                else:
                    continue
Solution().twoSum([2,7,11,15],9)

这个代码一是我看错了输出要求,但是后来改成了

list.append((i,j))

之后就开始疯狂输出[],然后改了一遍又一遍,中途把全局变量放到方法里面去也不行,然后干脆删了变量。。。。。。
最后是我成功通过的代码:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    return [i,j]
                    break
                else:
                    continue
Solution().twoSum([2,7,11,15],9)

对比之后我感觉,要在leetcode上想要正确输出,可能:
第一:最好不要改动它给的模板
第二:最好不要用全局变量
但是说实话,我到现在还是有点莫名其妙,一题搞了我一个小时,呜呜呜呜
而且看到题就想到用双层循环,最后跪在输出上,不行,想想还是好气!!!!!!!!!!!!!!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值