Python实现"第三大的数"的两种方法

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

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

1:注意例子中标红的地方,当第三个最大的数不存在时,输出第一个最大的数。此外,这三个最大的数彼此之间不能重复(效率较低:36s)

def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        com = [float("-inf")] * 3          #代替存储三个最大的数
        for i in range(len(nums)):         #时间复杂度O(n)
            for j in range(-1, -4, -1):    #倒序访问con列表
                if nums[i] > com[j]:       #按规则循环替换三个最大的数
                    com[j], nums[i] = nums[i], com[j]
                elif nums[i] == com[j]:   #如果当前数和三个最大的数之一重复,就结束内层for循环
                    break
        return com[2] if com[0] == float("-inf") else com[0]

参考他人:

def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max1 = max2 = max3 = None
        for num in nums:
            if num >max1:
                max2,max3 = max1,max2
                max1 = num
            elif num < max1 and num >max2:
                max3,max2 = max2,num
            elif num > max3 and num < max2:
                max3= num
        return max1 if max3 is None else max3

2:利用set()去除列表中重复数字,再转列表为nums,接着用nums.sort()方法对列表排序(参考他人,但该方法无法保证满足时间复杂O(n)的条件)

def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums = list(set(nums))
        nums.sort()
        if len(nums)<3:
            return nums[-1]
        else:
            return nums[-3]

参考他人:

def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dic = { }
        for num in nums:
            if num in dic:
                dic[num] += 1
            else:
                dic[num] = 1
        d = sorted(dic.keys())
        if len(d) >= 3:
            return d[-3]
        else:
            return max(d)

算法题来自:https://leetcode-cn.com/problems/third-maximum-number/description/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值