LeetCode : 176. Second Highest Salary
Second Highest Salary - LeetCode
문제
Table: Employee
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| salary | int |
+-------------+------+
id is the primary key (column with unique values) for this table.
Each row of this table contains information about the salary of an employee.
Write a solution to find the second highest salary from the Employee table. If there is no second highest salary, return null (return None in Pandas).
The result format is in the following example.
Example 1:
Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
Output:
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
Example 2:
Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
+----+--------+
Output:
+---------------------+
| SecondHighestSalary |
+---------------------+
| null |
+---------------------+
문제풀이
import pandas as pd
def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame:
salary = employee['salary'].unique()
salary.sort()
if len(salary) > 1:
return pd.DataFrame({'SecondHighestSalary': [salary[-2]]})
else:
return pd.DataFrame({'SecondHighestSalary': [None]})
- Salary가 두 번째로 큰 값을 찾아야 한다.
- 고려해야 할 점은, 두 번째로 큰 값이 없으면 Null값을 반환해야 한다.
- unique()를 통해서 급여 정보를 받아오고 정렬한다.
- 만약 salary 길이가 1보다 큰 경우에는 주어진 조건에 맞춰서 2번째로 큰 값을 가져온다.
- 그렇지 않은 경우에는 None을 반환
코멘트
- {col name1 : [v1, v2] } 이런 식으로 컬럼 뒤에는 iterable 가능한 List나 Tuple을 넣어야한다.
- 그냥 단일 값 넣어서 실수
'Data Analysis > Query' 카테고리의 다른 글
리트코드 : 180. Consecutive Numbers (0) | 2024.03.25 |
---|---|
리트코드 : 178. Rank Scores (0) | 2024.03.25 |
리트코드 : 177. Nth Highest Salary (0) | 2024.03.24 |
[MySQL] 프로그래머스 Lv.4 Lv.5 (0) | 2024.03.04 |
[MySQL] 프로그래머스 Lv.3 (0) | 2024.01.11 |
[MySQL] 프로그래머스 Lv.2 (0) | 2024.01.08 |
[MySQL] 프로그래머스 Lv.1 (0) | 2024.01.01 |
댓글