104 - 414第三大的数

题目

给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。

示例 1:

输入: [3, 2, 1]

输出: 1

解释: 第三大的数是 1.

示例 2:

输入: [1, 2]

输出: 2

解释: 第三大的数不存在, 所以返回最大的数 2 .

示例 3:

输入: [2, 2, 3, 1]

输出: 1

解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。 存在两个值为2的数,它们都排第二。

解答

第一反应是,用set和排序,然后输出第三大的数。。

Runtime: 76 ms, faster than 27.54% of JavaScript online submissions for Third Maximum Number.

Memory Usage: 38.1 MB, less than 25.00% of JavaScript online submissions for Third Maximum Number.

Runtime: 60 ms, faster than 84.99% of Python3 online submissions for Third Maximum Number.

Memory Usage: 15.1 MB, less than 7.69% of Python3 online submissions for Third Maximum Number.

当然go就没这么方便的函数了,得自己写。。

Runtime: 8 ms, faster than 6.48% of Go online submissions for Third Maximum Number.

Memory Usage: 4 MB, less than 100.00% of Go online submissions for Third Maximum Number.

维护三个变量

作者:happy_yuxuan

链接:https://leetcode-cn.com/problems/third-maximum-number/solution/414-kong-jian-o1-shi-jian-onliang-chong-fang-fa-he/

红黑树有点厉害了。。js好像没有要手写一个。。

Runtime: 60 ms, faster than 70.66% of JavaScript online submissions for Third Maximum Number.

Memory Usage: 35.1 MB, less than 100.00% of JavaScript online submissions for Third Maximum Number.

Runtime: 68 ms, faster than 45.74% of JavaScript online submissions for Third Maximum Number.

Memory Usage: 36.1 MB, less than 75.00% of JavaScript online submissions for Third Maximum Number.

变成数组的写法,似乎更加低效了。。

Runtime: 0 ms, faster than 100.00% of Go online submissions for Third Maximum Number.

Memory Usage: 3.2 MB, less than 100.00% of Go online submissions for Third Maximum Number.

Runtime: 4 ms, faster than 91.67% of Go online submissions for Third Maximum Number.

Memory Usage: 3 MB, less than 100.00% of Go online submissions for Third Maximum Number.

go的非数组写法反而要慢一点😂

Runtime: 60 ms, faster than 84.99% of Python3 online submissions for Third Maximum Number.

Memory Usage: 14.6 MB, less than 7.69% of Python3 online submissions for Third Maximum Number.

Runtime: 64 ms, faster than 60.85% of Python3 online submissions for Third Maximum Number. Memory Usage: 14.4 MB, less than 7.69% of Python3 online submissions for Third Maximum Number.

Last updated

Was this helpful?