huginn muninn

[leetcode] 626. Exchange Seats 본문

코딩테스트

[leetcode] 626. Exchange Seats

_maddy 2024. 6. 27. 01:34

https://leetcode.com/problems/exchange-seats/description/?envType=study-plan-v2&envId=top-sql-50

 

 

 

  • 연속된 두 학생 마다 좌석 id를 바꾸는 솔루션을 작성, 학생수가 홀수인 경우 마지막 학생의 id는 교환되지 않는다.
  • 정렬된 결과를 id 오름차순
  • 학생 수가 홀수인 경우 마지막 학생의 Id는 교환되지 않음
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| student     | varchar |
+-------------+---------+
id is the primary key (unique value) column for this table.
Each row of this table indicates the name and the ID of a student.
id is a continuous increment.

 

Write a solution to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped.

Return the result table ordered by id in ascending order.

The result format is in the following example.

# Write your MySQL query statement below
-- 연속되 두 학생 마다 좌석 id를 바꾸는 솔루션을 작성, 학생수가 홀수인 경우 마지막 학생의 id는 교환되지 않는다. 
-- 정렬된 결과를 id 오름차순
-- 학생 수가 홀수인 경우 마지막 학생의 Id는 교환되지 않음

select 
    case 
        when s.id%2!=0 and s.id=(select count(s.id) from seat as s) then s.id
        when s.id%2=0 then s.id-1 else s.id+1 
        end as id,
    student 
from seat as s 
order by id

 

어떻게 풀지 고민을 많이 했는데 홀수이면서 마지막 id이면 바꾸지 않기, 홀수기만 하면 다음 id랑 바꾸고, 짝수면 전 id랑 바꾸는 방법을 떠올렸다. 그래서 위의 코드처럼 구현...