返回
LeetCode 176. 第二高的薪水 算法解析
后端
2023-12-16 11:38:41
大家好,我是小魔龙,Unity3D软件工程师,VR、AR,虚拟仿真方向。
今天这篇文章,我们来一起解析一下 LeetCode 的第 176 题,第二高的薪水。
这道题目的要求是,给你一个包含员工薪资信息的表格,你需要找出第二高的薪水。
这道题目乍一看比较简单,但是其实有一些需要注意的地方。
首先,我们需要考虑如何处理重复的薪水。
例如,如果有多个员工的薪水相同,那么我们应该如何确定第二高的薪水呢?
一种简单的方法是,我们可以先对薪水进行排序,然后找出第二大的薪水。
但是,这样做的效率比较低,因为我们需要对整个表格进行排序。
一种更有效的方法是,我们可以使用哈希表来存储薪水和员工数量。
这样,我们只需要遍历一遍表格,就可以统计出每个薪水对应的员工数量。
然后,我们可以找出员工数量最大的薪水,以及员工数量第二大的薪水。
这样,我们就得到了第二高的薪水。
具体代码如下:
def second_highest_salary(salaries):
"""
Find the second highest salary in a table of employee salaries.
Args:
salaries: A list of employee salaries.
Returns:
The second highest salary in the table.
"""
# Create a hash table to store the salary and the number of employees
# who earn that salary.
salary_counts = {}
for salary in salaries:
if salary not in salary_counts:
salary_counts[salary] = 0
salary_counts[salary] += 1
# Find the salary with the maximum number of employees.
max_salary = None
max_count = 0
for salary, count in salary_counts.items():
if count > max_count:
max_salary = salary
max_count = count
# Find the salary with the second maximum number of employees.
second_max_salary = None
second_max_count = 0
for salary, count in salary_counts.items():
if salary != max_salary and count > second_max_count:
second_max_salary = salary
second_max_count = count
# Return the second highest salary.
return second_max_salary
# Test the function.
salaries = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
print(second_highest_salary(salaries))
运行结果如下:
9000
好了,以上就是 LeetCode 第 176 题,第二高的薪水的算法解析。
希望对大家有所帮助。