[逐日一练]利用“笛卡尔合并”判定数据是否连续
#该题目泉源于力扣:603. 连续空余座位 - 力扣(LeetCode)
题目要求:
表: Cinema
+-------------+------+
| 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 |
+---------+ 思路流程:
何谓笛卡尔合并?就是描述两个数据集间所有可能的组合。
简而言之,就是判定返回连续free列的值为1,且超过2个及其以上的所有对应seat_id的数据。
判定是否连续,且连续的要求要大于即是三个,判定连续的条件,不妨先对这张表做一个笛卡尔合并:
# Write your MySQL query statement below
select *
from cinema as a, cinema as b
可见,笛卡尔合并后的数据为:
| seat_id | free | seat_id | free |
| ------- | ---- | ------- | ---- |
| 5 | 1 | 1 | 1 |
| 4 | 1 | 1 | 1 |
| 3 | 1 | 1 | 1 |
| 2 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 |
| 5 | 1 | 2 | 0 |
| 4 | 1 | 2 | 0 |
| 3 | 1 | 2 | 0 |
| 2 | 0 | 2 | 0 |
| 1 | 1 | 2 | 0 |
| 5 | 1 | 3 | 1 |
| 4 | 1 | 3 | 1 |
| 3 | 1 | 3 | 1 |
| 2 | 0 | 3 | 1 |
| 1 | 1 | 3 | 1 |
| 5 | 1 | 4 | 1 |
| 4 | 1 | 4 | 1 |
| 3 | 1 | 4 | 1 |
| 2 | 0 | 4 | 1 |
| 1 | 1 | 4 | 1 |
| 5 | 1 | 5 | 1 |
| 4 | 1 | 5 | 1 |
| 3 | 1 | 5 | 1 |
| 2 | 0 | 5 | 1 |
| 1 | 1 | 5 | 1 | 可见笛卡而合并描述了两个聚集的所有可能的有序对组合。我们在捋清了每个笛卡尔组合的逻辑后,再进行后续的分析。
首先判定它们是否相邻,由上表可知,笛卡尔合并包罗了所有的组合情况,而且seat_id列是有先后顺序的。所有效a表和b表的seat_id互减,取绝对值为1,就可以判定出二者是相邻的。同时,要判定两个及其以上的座位都为空,那么要求a表和b表的free列的值都为1。逻辑如下:
# Write your MySQL query statement below
select *
from cinema as a, cinema as b
where abs(a.seat_id-b.seat_id)=1 and a.free=1 and b.free=1;/*| seat_id | free | seat_id | free || ------- | ---- | ------- | ---- || 4 | 1 | 3 | 1 || 5 | 1 | 4 | 1 || 3 | 1 | 4 | 1 || 4 | 1 | 5 | 1 |*/ 由此可见,所有相邻的,符合条件的座位号全部列了出来。但它们之间有空值,而且并未排序,我们对其稍加处置处罚,即可办理这个问题。
代码实现:
# Write your MySQL query statement below
select distinct a.seat_id
from cinema as a, cinema as b
where abs(a.seat_id-b.seat_id)=1 and a.free=1 and b.free=1
order by a.seat_id ASC
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]