首页 文章详情

​LeetCode刷题实战603:连续空余座位

程序IT圈 | 62 2022-05-10 23:03 0 0 0
UniSMS (合一短信)
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 连续空余座位,我们先来看题面:
https://leetcode.cn/problems/consecutive-available-seats/

解题

https://blog.csdn.net/qq_25886325/article/details/118635352


1、join

思路:只有一张表,需要通过seat_id自己连自己,条件是abs(c1.seat_id - c2.seat_id) = 1。
代码:

select

  distinct c1.seat_id

from cinema c1 join cinema c2

on abs(c1.seat_id - c2.seat_id) = 1 and c1.free = 1 and c2.free = 1

order by c1.seat_id;

2、row_number() over()

思路:
S1:使用窗口函数 row_number 对 cinema 进行排序,seat_id - row_number() over() as k ,如果座位连续,这组 k 值应该是相等的。
S2:将第一步和第二步的结果作为临时表 temp,将临时表 temp 按照 k 进行分组查询,并且筛选出大于 2 的 k 值
S3:从临时表 temp 中查询出 seat_id ,筛选出 k 值在第四步中的值

代码:

with temp as (

  select

    seat_id,

    seat_id - row_number() over() as k

  from cinema where free = 1

)

select seat_id from temp where k in (

  select k from temp group by k having count(*) >= 2

);


原文链接:https://blog.csdn.net/HeavenDan/article/details/123448972
上期推文:
LeetCode1-600题汇总,希望对你有点帮助!
LeetCode刷题实战601:体育馆的人流量
LeetCode刷题实战602:好友申请 II :谁有最多的好友

good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter