Skip to content

Commit 6af47cd

Browse files
[N-0] add 626
1 parent dbfd945 commit 6af47cd

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,7 @@ Your ideas/fixes/algorithms are more than welcome!
656656
| # | Title | Solutions | Time | Space | Difficulty | Tag | Notes
657657
|-----|----------------|---------------|---------------|---------------|-------------|--------------|-----
658658
|627|[Swap Salary](https://leetcode.com/problems/swap-salary/)|[Solution](../master/database/_627.sql) | | | Easy |
659+
|626|[Exchange Seats](https://leetcode.com/problems/exchange-seats/)|[Solution](../master/database/_626.sql) | | | Medium |
659660
|620|[Not Boring Movies](https://leetcode.com/problems/not-boring-movies/)|[Solution](../master/database/_620.sql) | | | Easy |
660661
|619|[Biggest Single Number](https://leetcode.com/problems/biggest-single-number/)|[Solution](../master/database/_619.sql) | | | Easy |
661662
|618|[Students Report By Geography](https://leetcode.com/problems/students-report-by-geography/)|[Solution](../master/database/_618.sql) | | | Hard | Session Variables

database/_626.sql

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
--626. Exchange Seats
2+
--
3+
--Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids.
4+
--
5+
--The column id is continuous increment.
6+
--Mary wants to change seats for the adjacent students.
7+
--Can you write a SQL query to output the result for Mary?
8+
--+---------+---------+
9+
--| id | student |
10+
--+---------+---------+
11+
--| 1 | Abbot |
12+
--| 2 | Doris |
13+
--| 3 | Emerson |
14+
--| 4 | Green |
15+
--| 5 | Jeames |
16+
--+---------+---------+
17+
--For the sample input, the output is:
18+
--+---------+---------+
19+
--| id | student |
20+
--+---------+---------+
21+
--| 1 | Doris |
22+
--| 2 | Abbot |
23+
--| 3 | Green |
24+
--| 4 | Emerson |
25+
--| 5 | Jeames |
26+
--+---------+---------+
27+
--Note:
28+
--If the number of students is odd, there is no need to change the last one's seat.
29+
30+
31+
SELECT
32+
(CASE
33+
WHEN MOD(id, 2) != 0 AND counts != id THEN id + 1
34+
WHEN MOD(id, 2) != 0 AND counts = id THEN id
35+
ELSE id - 1
36+
END) AS id,
37+
student
38+
FROM
39+
seat,
40+
(SELECT
41+
COUNT(*) AS counts
42+
FROM
43+
seat) AS seat_counts
44+
ORDER BY id ASC;

0 commit comments

Comments
 (0)