【LeeCode 数据结构】1. 两数之和
LeeCode地址 看起来很简单的一题结果提交的时候问题却不少。不想看过程可以直接翻到最后看提交代码。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IZm65Vfi-1576747266427)(1. 两数之和.assets/image-20191219162443056.png)]
问题1
第一次在LeeCode中答题。选择语言为Python3后,代码模板(如下)中的nums: List[int]
、target: int
和->List[int]
这种指明变量和返回值类型的方式令我惊奇。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
最开始以为是我孤陋寡闻(因为我以前不怎么用 类 这种方式变成,都是直接上函数面向过程编程),不知道Python中有这种用法,但是复制代码后放到Notepad++中运行却报错List未定义
,说明这是LeeCode中特有的。
事实上删掉这些对变量类型的指示后(如下),在LeeCode中也能提交通过(已测试),所以以后都删掉吧,方便在别的环境中运行。
class Solution:
def twoSum(self, nums, target):
问题2
第一思路是直接两层嵌套的循环进行搜索,代码如下:
class Solution:
def twoSum(self, nums, target):
n = len(nums)
for i in range(n):
for j in range(n):
if i != j and nums[i] + nums[j] == target:
return [i, j]
提交后说超出时间限制
,搜了一下有博客提到时间复杂度的概念,确实,这种时间复杂度为
n
2
n^2
n2 , 并且提到很有意思的一点,说在第2个循环里不必遍历全部n个数,只要遍历从i+1到n之间的即可!想想确实,若:
第1层循环 [ x 1 , x 2 , x 3 , x 4 , x 5 ] [x_1, x_2, x_3, x_4, x_5] [x1,x2,x3,x4,x5] 结果为 x 3 x_3 x3
第2层循环 [ x 1 , x 2 , x 3 , x 4 , x 5 ] [x_1, x_2, x_3, x_4, x_5] [x1,x2,x3,x4,x5] 结果为 x 1 x_1 x1
这种情况实际是不能出现的,因为若这种满足要求,则在第1层
x
1
x_1
x1、第2层
x
3
x_3
x3就已经return
结束了。
我的提交
class Solution:
def twoSum(self, nums, target):
n = len(nums)
for i in range(n):
x = nums[i]
y = target - x
nums_rest = nums[(i+1):] # 只在后面搜索即可
if y in nums_rest:
j = nums_rest.index(y) + i + 1 # 但返回index的时候还是应该加上前面i+1个的
return [i, j]
执行结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IZhNRQTU-1576747266428)(1. 两数之和.assets/image-20191219170552239.png)]