1. 程式人生 > >leetcode 180. Consecutive Numbers 解題思路

leetcode 180. 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.

發現網上的大多數思路都用到了自定義變數,並且比較麻煩

個人解題的時候用了個土辦法。

如下:

select distinct Num as ConsecutiveNums  from Logs as l
where l.num = 
(select num from Logs as p where l.id+2=p.id )
&&
l.num = 
(select num from Logs as p where l.id+1=p.id )

簡單粗暴- -。判斷連續三個是否num相等。