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