前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-414-第三大的数

leetcode-414-第三大的数

作者头像
Spaceack
发布2020-11-04 14:35:49
3310
发布2020-11-04 14:35:49
举报
文章被收录于专栏:编程使我快乐

题目描述

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

示例

示例 1:

代码语言:javascript
复制
输入: [3, 2, 1]

输出: 1

解释: 第三大的数是 1.

示例 2:

代码语言:javascript
复制
输入: [1, 2]

输出: 2

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

示例 3:

代码语言:javascript
复制
输入: [2, 2, 3, 1]

输出: 1

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

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/robot-return-to-origin


  • 解题思路 首先用苯办法,定义一个最大长度为三的有序列表,依次从nums列表中取值,插入该有序列表。 优点是节约内存, 缺点是判断比较麻烦。

题解1:

执行用时:80 ms, 在所有 Python3 提交中击败了21.76%的用户

内存消耗:14.4 MB, 在所有 Python3 提交中击败了92.21%的用户

代码语言:javascript
复制
from typing import List
class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        # 默认右边最大
        th = []
        while nums:
            num = nums.pop()
            if num in th:
                continue
            if not th:
                th.append(num)
            if len(th) == 1:
                if num > th[0]:
                    th.append(num)
                elif num < th[0]:
                    th.insert(0, num)
                # 这里需要注意, 第二次因为没有continue.会执行到下面的判断,低级错误。
                continue
            if len(th) == 2:
                if num > th[1]:
                    th.append(num)
                elif num < th[0]:
                    th.insert(0, num)
                elif num > th[0]:
                    th.insert(1, num)
                continue
            if len(th) == 3:
                if num > th[2]:
                    th.append(num)
                    del th[0]
                elif num < th[0]:
                    continue
                elif num > th[0] and num < th[1]:
                    del th[0]
                    th.insert(0, num)
                elif num > th[1] and num < th[2]:
                    del th[0]
                    th.insert(1, num)
                continue
                # 这里需要注意, 第一次提交下标写的是2,没有考虑到1的情况,要用反向索引-1
        return th[-1] if len(th) < 3 else th[0]
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档