Leetcode 求二叉树的最大深度问题,为什么这两种解法耗时会相差两倍?

2018-12-08 12:25:18 +08:00
 Deardrops

题目:给定一个二叉树,找出其最大深度。 语言:Golang

解法①:

// 16ms, beat 12.46%
func maxDepth(root *TreeNode) int {
	if root == nil {
		return 0
	}
	leftDepth := maxDepth(root.Left)
	rightDepth := maxDepth(root.Right)
	if leftDepth > rightDepth {
		return leftDepth + 1
	} else {
		return rightDepth + 1
	}
}

解法②:

// 8ms, beat 100%
func maxDepth(root *TreeNode) int {
	if root != nil {
		leftDepth := maxDepth(root.Left)
		rightDepth := maxDepth(root.Right)
		if leftDepth > rightDepth {
			return 1+leftDepth
		}
		return 1+rightDepth
	}
	return 0
}

实际提交到 leetcode 上,前者耗时 16ms,后者耗时 8ms。

初学 Golang,请问这两段代码为什么执行时间会差两倍?

3658 次点击
所在节点    Go 编程语言
14 条回复
Jex
2018-12-08 12:33:47 +08:00
要先学会正确的性能测试方法
notreami
2018-12-08 12:47:57 +08:00
第一个解法,我这边运行是 8ms
做第一个题的时候,就发现同样的代码,执行结果耗时有差异,猜测可能是 gc,或者资源排队等问题。
lhx2008
2018-12-08 12:55:51 +08:00
leetcode 的隔离很差,波动大也很正常
Deardrops
2018-12-08 12:56:39 +08:00
@notreami 感谢解答,还以为代码里有什么高深莫测的东西。
kaitian521
2018-12-08 13:20:47 +08:00
c
kaitian521
2018-12-08 13:22:16 +08:00
试一下 maxDepth(root.Left)>maxDepth(root.Right)? 1+maxDepth(root.Left): 1+maxDepth(root.Right);
msg7086
2018-12-08 13:23:07 +08:00
你自己拿个秒表,掐两次,然后想想为什么其中一次会是另一次时间的两三倍,就知道原因了。
hxd
2018-12-08 13:39:30 +08:00
你自己同一个解法不同时间再提交,也可能差两倍
azuki
2018-12-08 15:22:46 +08:00
@hxd 对的。
onepunch
2018-12-08 15:35:07 +08:00
运行一万次的时间 / 10000 是每次运行的时间 [手动狗头]
zzj0311
2018-12-08 16:28:47 +08:00
leetcode 时间并不能作为性能测试的依据,特别是几个 ms 的那种
gqw121314
2018-12-08 17:18:23 +08:00
我相同的代码重复提交了 3 次,每次时间都不一样。。。
akira
2018-12-08 18:34:35 +08:00
以 ms 为单位的性能统计,±50ms 很正常的
bubuhere
2018-12-08 19:02:02 +08:00
leetcode 给出的时间没有太大参考性

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/515595

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX