码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode——Consecutive Numbers

时间:2019-10-09 15:26:12      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:rom   tin   enum   from   number   statement   least   log   tco   

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 below
SELECT 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 below
SELECT 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;

此版本,效率得到了巨大的提高。

LeetCode——Consecutive Numbers

标签:rom   tin   enum   from   number   statement   least   log   tco   

原文地址:https://www.cnblogs.com/jason1990/p/11641911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!