leetcode-Consecutive numbers

Write a SQL query to find all numbers that appear at least three times consecutively.

+----+-----+
| Id | Num |
+----+-----+
| 1  |  1  |
| 2  |  1  |
| 3  |  1  |
| 4  |  2  |
| 5  |  1  |
| 6  |  2  |
| 7  |  2  |
+----+-----+

For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times.


 

思路:

自己没看题解做出来的第一道middle难度的题目,这个题和Rasing Temprature很像,考察的都是一个表中不同元组之间的某些属性的比较

那个easy的题目只要比较连续的两行就好,而这个题目要比较三行

将easy题目的两种解法套用过来,其中一个会超时,及O(2n^2)时间复杂度的那个嵌套选择算法,我分析这种算法之所以超时是因为每一次子select都要遍历整张表来判断where a.Id = c.Id - 2和where a.Id = b.Id-1,而当表的数据非常大的时候,速度就会很慢

第二种AC了的算法,感觉是一种消耗空间节省时间的方法,我们建立了表格之后,只需要遍历一遍就可以得出最后的答案。


AC代码:
select distinct a.Num as consecutiveNums from Logs as a,Logs as b,Logs as c where a.Id = b.Id - 1 and a.Id = c.Id - 2 and a.Num = b.Num and a.Num = c.Num

 

TLE代码:
select distinct a.Num as ConsecutiveNums
from Logs as a
where a.Num = (
select b.Num 
from Logs as b
where a.Id = b.Id -1
)
and
a.Num = (
select c.Num
from Logs as c
where a.Id = c.Id -2
)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值