返回
算法案例修炼指南|54.第三大的数|LeetCode每日刷题挑战赛
前端
2023-12-27 09:54:10
前言
作为一名技术爱好者,算法是通往编程世界的必经之路。为了帮助大家夯实算法基础,提升解决问题的能力,我们隆重推出【算法千题案例】⚡️每日LeetCode打卡⚡️系列文章,从LeetCode精选题库中甄选经典题目,进行深入剖析和讲解,助力大家征服算法挑战,成为算法达人。
题目背景
今天,我们聚焦于LeetCode的第54题——第三大的数。题目要求给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。
示例
为了帮助大家更好地理解题意,我们先来看几个示例:
示例1:
输入:nums = [3, 2, 1]
输出:1
示例2:
输入:nums = [1, 2]
输出:2
示例3:
输入:nums = [2, 2, 3, 1]
输出:1
算法解析
对于这道题目,我们可以采用以下算法来求解:
-
排序法:
- 将数组中的元素进行排序。
- 由于题目要求的是第三大的数,我们可以直接返回排序后数组中的第三个元素。
- 如果数组中元素个数少于3,则返回数组中最大的数。
-
哈希法:
- 使用哈希表来记录数组中的元素。
- 遍历数组,将每个元素作为哈希表的键,并将其值设置为出现的次数。
- 然后,根据哈希表中的值,我们可以找出出现次数最少的第三个元素。
- 如果数组中元素个数少于3,则返回数组中最大的数。
代码实现
根据上述算法,我们可以使用Python语言实现如下代码:
def third_max(nums):
"""
Find the third maximum number in an array.
Args:
nums: A non-empty array of integers.
Returns:
The third maximum number in the array. If there are less than three
distinct numbers in the array, return the maximum number.
"""
# Sort the array in descending order.
nums.sort(reverse=True)
# Initialize a set to store unique numbers.
unique_nums = set()
# Iterate over the sorted array.
for num in nums:
# Add the number to the set if it is not already there.
if num not in unique_nums:
unique_nums.add(num)
# If we have found three unique numbers, return the third one.
if len(unique_nums) == 3:
return num
# If we have not found three unique numbers, return the maximum number.
return nums[0]
# Test the function.
print(third_max([3, 2, 1])) # 1
print(third_max([1, 2])) # 2
print(third_max([2, 2, 3, 1])) # 1
结语
通过对LeetCode第54题——第三大的数的分析和讲解,相信大家对算法思维有了更深入的理解。算法题看似复杂,但只要掌握正确的解题方法,就能轻松应对。希望大家能够积极参与【算法千题案例】⚡️每日LeetCode打卡⚡️系列文章的学习,不断提升自己的算法水平,在编程的道路上越走越远!