先看题目
+-------------+------+
| Column Name | Type |
+-------------+------+
| seat_id | int |
| free | bool |
+-------------+------+
Seat_id 是该表的自动递增主键列。
在 PostgreSQL 中,free 存储为整数。请使用 ::boolean 将其转换为布尔格式。
该表的每一行表示第 i 个座位是否空闲。1 表示空闲,0 表示被占用。
查找电影院所有连续可用的座位。
返回按 seat_id
升序排序 的结果表。
测试用例的生成使得两个以上的座位连续可用。
结果表格式如下所示。
示例 1:
输入:
Cinema 表:
+---------+------+
| seat_id | free |
+---------+------+
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
+---------+------+
输出:
+---------+
| seat_id |
+---------+
| 3 |
| 4 |
| 5 |
+---------+
表格构建代码如下
drop table Cinema;
Create table Cinema (seat_id number primary key, free varchar(2));
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');
commit;
本题还是按照上一篇文章(力扣篇--3)的思路 构造两个数列来做 , 第一个数列还是用seat_id 就可以
第二个数列还是用窗口函数排一个名
如下
with t1 as (
select
seat_id,
free,
row_number() over (partition by free order by seat_id) rank ,
seat_id - row_number() over (partition by free order by seat_id) diff
from CINEMA
where free=1
)
, t2 as (
select
seat_id,
free,
rank ,
diff,
count(seat_id) over (partition by diff) cnt
from t1
)
select
seat_id
from t2
where cnt>=3
order by seat_id
此题由于和之前内容套路有重复 , 所以就直接给出答案 , 然后外加说明一下, 我们最后得出连续的次数之后还要再使用一次窗口函数去 count 一下连续的次数并且新增一行这个次数的数量 , 这块区别于上一题直接聚合求连续次数
为什么要做这一步呢 ? 因为题目要求输出连续的座位号 , 我们求出连续的次数没有用 , 不是人家最重要的答案 , 只能作为中间过渡一下 , 用于过滤连续次数大于 2 的座位号序列
结尾欢迎大家点赞收藏加评论,后续会持续更新题目,无需力扣plus会员也能做题 ~ ~ ~