본문 바로가기
Data Analysis/Query

리트코드 : 177. Nth Highest Salary

by 베짱이28호 2024. 3. 24.

리트코드 : 177. Nth Highest Salary

Nth Highest Salary - LeetCode

 


문제

'''
+-------------+------+
| 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 nth highest salary from the Employee table. If there is no nth highest salary, return null.

The result format is in the following example.

 

Example 1:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
n = 2
Output: 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+
Example 2:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
n = 2
Output: 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| null                   |
+------------------------+
'''

 

문제풀이

import pandas as pd

def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame:

    salary = list(employee['salary'].unique())
    salary.sort(reverse=True)

    if len(salary) < N or N <= 0:
        return pd.DataFrame({f'getNthHighestSalary({N})':[None]})
    else:
        return pd.DataFrame({f'getNthHighestSalary({N})':[salary[N-1]]})
  • unique를 통해서 salary의 고유한 값을 가져온다.
  • 내림차순으로 정렬 후, 앞에서 N번 째 값을 가져오기.
  • 입력 N이 음수가 들어오는 경우가 있어서 예외 처리를 해야한다.

 

def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame:

    employee['dense_rank'] = employee['salary'].rank(method='dense',ascending=False).astype(int)
    Nth_salary = employee[employee['dense_rank'] == N]['salary']

    if Nth_salary.empty:
        Nth_salary = None
    else:
        Nth_salary = Nth_salary.iloc[0]
    return pd.DataFrame({f'getNthHighestSalary({N})' : [Nth_salary]})
  • rank의 dense를 통해서 SQL의 dense rank처럼 등수를 매겨준다.
  • 조건을 걸어서 매긴 등수만 일치하면 ok
  • 맞는 조건의 등수가 없을 수 있어서 empty로 체크를 해준다.
  • 조건으로 가져온 Nth_salary는 int가 아니라 Series 형태이기 때문에 iloc[0]으로 값을 가져와줘야 한다.

  • 코멘트
  • 처음엔 1번 풀이로 풀었는데, 1번보단 2번 풀이가 더 좋아보인다.
  • 동작 속도는 크게 차이는 안나는데 N이 음수인 경우도 들어와서 조건식 처리하는게 조금 더 편한 느낌?
  • 시리즈, 데이터 프레임이 비어 있을때는 empty를 사용한다.
  • rank에는 SQL dense rank처럼 method를 지정할 수 있고, 정렬과 마찬가지로 오름차순, 내림차순을 사용 가능하다.

댓글