180. Consecutive Numbers

来源:互联网 发布:腾讯算法面试题 编辑:程序博客网 时间:2024/06/11 03:37

题目:

找出连续出现大于或等于3次的数字。
Logs

Id Num 1 1 2 1 3 1 4 2 5 1 6 2 7 2

例如:1连续出现3次,结果如下。

ConsecutiveNums 1

解析

表内的联系,通常采用表的自连接。题目中主要涉及表内连续3次出现同一数字,那么就需要3张表做连接。

select distinct a.num as ConsecutiveNumsfrom Logs as ajoin Logs as b on a.id=b.id-1join Logs as c on a.id=c.id-2 where a.num=b.num and b.num=c.num

表a,b,c分别代表了第一次出现的数字,第二次出现的数字以及第三出现的数字。如果三次都相同,那么即为该数连续出现3次。此外,如果连续出现3次以上那么就会输出多个相同的满足条件的值,因此需要distinct去重。
另一种解法为:

select distinct a.Num as ConsecutiveNums from     Logs as a,     Logs as b,     Logs as cwhere     a.Num = b.Num and b.Num = c.Num    and a.Id=b.Id-1     and b.Id= c.Id-1
原创粉丝点击