返回介绍

solution / 0600-0699 / 0603.Consecutive Available Seats / README_EN

发布于 2024-06-17 01:03:36 字数 3076 浏览 0 评论 0 收藏 0

603. Consecutive Available Seats

中文文档

Description

Table: Cinema

+-------------+------+
| Column Name | Type |
+-------------+------+
| seat_id   | int  |
| free    | bool |
+-------------+------+
seat_id is an auto-increment column for this table.
Each row of this table indicates whether the ith seat is free or not. 1 means free while 0 means occupied.

 

Find all the consecutive available seats in the cinema.

Return the result table ordered by seat_id in ascending order.

The test cases are generated so that more than two seats are consecutively available.

The result format is in the following example.

 

Example 1:

Input: 
Cinema table:
+---------+------+
| seat_id | free |
+---------+------+
| 1     | 1  |
| 2     | 0  |
| 3     | 1  |
| 4     | 1  |
| 5     | 1  |
+---------+------+
Output: 
+---------+
| seat_id |
+---------+
| 3     |
| 4     |
| 5     |
+---------+

Solutions

Solution 1: Self-Join

We can use a self-join to join the Seat table with itself, and then filter out the records where the id of the left seat is equal to the id of the right seat minus $1$, and where both seats are empty.

# Write your MySQL query statement below
SELECT DISTINCT a.seat_id
FROM
  Cinema AS a
  JOIN Cinema AS b ON ABS(a.seat_id - b.seat_id) = 1 AND a.free AND b.free
ORDER BY 1;

Solution 2: Window Function

We can use the LAG and LEAD functions (or SUM() OVER(ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)) to obtain the information of adjacent seats, and then filter out the consecutive empty seats and sort them in a unique way.

# Write your MySQL query statement below
WITH
  T AS (
    SELECT
      seat_id,
      (free + (LAG(free) OVER (ORDER BY seat_id))) AS a,
      (free + (LEAD(free) OVER (ORDER BY seat_id))) AS b
    FROM Cinema
  )
SELECT seat_id
FROM T
WHERE a = 2 OR b = 2;

Solution 3

# Write your MySQL query statement below
WITH
  T AS (
    SELECT
      *,
      SUM(free = 1) OVER (
        ORDER BY seat_id
        ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
      ) AS cnt
    FROM Cinema
  )
SELECT seat_id
FROM T
WHERE free = 1 AND cnt > 1
ORDER BY 1;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文