603. 连续空余座位

Leetcode题目:自联结

表: Cinema

+-------------+------+
| Column Name | Type |
+-------------+------+
| seat_id     | int  |
| free        | bool |
+-------------+------+
在 SQL 中,Seat_id 是该表的自动递增主键列。
该表的每一行表示第 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       |
+---------+

解题思路

自联结

一开始想的是自联结,但是写了发现过不了。仔细看了看不能写A.seat_id+1 = B.seat_id OR A.seat_id-1=B.seat_id。只能用ABS求绝对值。

好吧,又试了下发现是一开始自联结用的where而不是on才没过测试,怪不得。

# Write your MySQL query statement below
SELECT DISTINCT A.seat_id
FROM Cinema AS A
INNER JOIN Cinema AS B 
ON A.seat_id-1=B.seat_id OR A.seat_id+1=B.seat_id
WHERE A.free=1 AND B.free=1
ORDER BY A.seat_id ASC
Subscribe
提醒
0 评论
Inline Feedbacks
View all comments
0
在此留下你的评论x