LeetCode-603. 连续空余座位

几个朋友来到电影院的售票处,准备预约连续空余座位。

你能利用表 cinema ,帮他们写一个查询语句,获取所有空余座位,并将它们按照 seat_id 排序后返回吗?

| seat_id | free |
|---------|------|
| 1       | 1    |
| 2       | 0    |
| 3       | 1    |
| 4       | 1    |
| 5       | 1    |
 

对于如上样例,你的查询语句应该返回如下结果。

| seat_id |
|---------|
| 3       |
| 4       |
| 5       |
注意:

seat_id 字段是一个自增的整数,free 字段是布尔类型('1' 表示空余, '0' 表示已被占据)。
连续空余座位的定义是大于等于 2 个连续空余的座位。

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/consecutive-available-seats

审题:和601体育馆连续三天人流量类似。

思考:

解题:

解法一:

先查出连续两天的集合:

select A1.seat_id as id1,A2.seat_id as id2
from cinema as A1 
join cinema as A2 on(A1.seat_id+1 = A2.aeat_id and A1.free = 1 and A2.free = 1)

 id1,id2都是满足条件的,

和原表连接,取出这些,去重。


SELECT DISTINCT S.*
from(
select A1.seat_id as id1,A2.seat_id as id2
from cinema as A1 
join cinema as A2 on(A1.seat_id+1 = A2.aeat_id and A1.free = 1 and A2.free = 1)
)as A
join cinema as S on(A.id1 = S.id or A.id2 = S.id)

解法二:

大于等于 2 个连续空余的座位 成为 连续空余座位。

座位的seat_id连续自增。

表自连接。找出所有相邻的空位。相邻的座位指seat_id相差为1的座位。

并按seat_id排序 。

select distinct C1.seat_id
from cinema as C1 join cinema as C2
    on(C1.free='1' and C2.free='1' and (C1.seat_id+1=C2.seat_id or C1.seat_id-1=C2.seat_id))
order by C1.seat_id

知识点: 

发布了84 篇原创文章 · 获赞 2 · 访问量 2629

猜你喜欢

转载自blog.csdn.net/Hello_JavaScript/article/details/103388520