[LeetCode] 626. 换座位

xiaoxiao2021-03-01  53

小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。

其中纵列的 id 是连续递增的。小美想改变相邻俩学生的座位 ?

示例:

+---------+---------+ | id | student | +---------+---------+ | 1 | Abbot | | 2 | Doris | | 3 | Emerson | | 4 | Green | | 5 | Jeames | +---------+---------+

假如数据输入的是上表,则输出结果如下:

+---------+---------+ | id | student | +---------+---------+ | 1 | Doris | | 2 | Abbot | | 3 | Green | | 4 | Emerson | | 5 | Jeames | +---------+---------+

注意:

如果学生人数是奇数,则不需要改变最后一个同学的座位。

解答思路:

对照上表及其查询结果可以得知,当原id为奇数时,交换座位后的id变为id+1,当原id为偶数时,交换座位后的id变为id-1,另一个方面需要考虑的是,学生人数为奇数时,最后一个学生的id不变,故应当用子查询确定学生的人数,然后分情况讨论即可。

Mod()返回除操作的余数(取模) 如:mod(id, 2) = 1 ===> 返回id号是奇数的id

# Write your MySQL query statement below select (case when mod(id,2)!=0 and id!=counts then id+1 when mod(id,2)!=0 and id=counts then id else id-1 end)as id,student from seat,(select count(*)as counts from seat)as seat_counts order by id;
参考链接:Mysql| Mysql函数,聚集函数的介绍与使用(Lower,Date,Mod,AVG,…)
转载请注明原文地址: https://www.6miu.com/read-4150009.html

最新回复(0)