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.+-----------------+| ConsecutiveNums |+-----------------+| 1 |+-----------------+
题意:求表中连续出现3次以上的数据.
因此,根据题意构造第一版本答案(使用连续的ID进行比较):
# Write your MySQL query statement belowSELECT DISTINCT t1.Num AS ConsecutiveNums FROM Logs t1, Logs t2, Logs t3 WHERE t1.Id = t3.Id - 1 AND t2.Id = t3.Id + 1 AND t1.Num = t2.Num AND t2.Num = t3.Num;
当前版本答案通过了测试,但是运行效率太低了.
分析原因,可能与t1.Id = t3.Id - 1
条件相关,当t3.Id
为0时,-1不会寻找到相关数据,导致sql
执行缓慢.
因此,修改为如下所示:
# Write your MySQL query statement below# Write your MySQL query statement belowSELECT DISTINCT t1.Num AS ConsecutiveNums FROM Logs t1, Logs t2, Logs t3 WHERE t2.Id = t1.Id + 1 AND t3.Id = t1.Id + 2 AND t1.Num = t2.Num AND t2.Num = t3.Num;
此版本,效率得到了巨大的提高。
PS:
如果您觉得我的文章对您有帮助,请关注我的微信公众号,谢谢!
赞 (0)