题目描述

(通过次数22,662 | 提交次数35,073,通过率64.61%)

表:Cinema
+-------------+------+
| Column Name | Type |
+-------------+------+
| seat_id     | int  |
| free        | bool |
+-------------+------+
Seat_id是该表的自动递增主键列。
该表的每一行表示第i个座位是否空闲。1表示空闲,0表示被占用。

编写一个SQL查询来报告电影院所有连续可用的座位。
返回按 seat_id 升序排序的结果表。
测试用例的生成使得两个以上的座位连续可用。

查询结果格式如下所示。
示例 1:
输入: 
Cinema 表:
+---------+------+
| seat_id | free |
+---------+------+
| 1       | 1    |
| 2       | 0    |
| 3       | 1    |
| 4       | 1    |
| 5       | 1    |
+---------+------+
输出: 
+---------+
| seat_id |
+---------+
| 3       |
| 4       |
| 5       |
+---------+

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/consecutive-available-seats
--测试数据
Create table If Not Exists Cinema (seat_id int primary key auto_increment, free bool);

insert into Cinema (seat_id, free) values ('1', '1');
insert into Cinema (seat_id, free) values ('2', '0');
insert into Cinema (seat_id, free) values ('3', '1');
insert into Cinema (seat_id, free) values ('4', '1');
insert into Cinema (seat_id, free) values ('5', '1');

解题思路

这仍然是一道连续区间的问题,小伙伴们可以通过传送门查看1454. 活跃用户(难度:困难)中的解题思路,这里就不再赘述了。

参考SQL

未特别说明的情况下,参考SQL为基于MySQL8.0实现。
with
tmp as (
    select
        seat_id,
        seat_id - row_number() over(order by seat_id) rn_diff
    from Cinema
    where free = 1
)
select
    seat_id
from tmp
where rn_diff in (
    select
        rn_diff
    from tmp a
    group by rn_diff
    having count(1)>=2
);
picture loss