LeetCode每天一题

180. 连续出现的数字

180. 连续出现的数字

难度中等272

SQL架构

编写一个 SQL 查询,查找所有至少连续出现三次的数字。

1
2
3
4
5
6
7
8
9
10
11
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+

例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。

1
2
3
4
5
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1 |
+-----------------+

通过次数38,537

提交次数78,477

解题思路

使用自身连接查询,首先要判断哪个是至少三次连续出现的数字

这里就可以使用自身查询,条件如下:

1
2
3
4
l1.Id=l2.Id-1
and l2.Id=l3.Id-1
and l1.Num=l2.Num
and l2.Num=l3.Num;

然后就很简单啦,直接查询输出即可。

但是这里要用distinct去重一下。因为如果一个数字连续出现超过 3 次,会返回重复元素。

答案解析

1
2
3
4
5
6
7
# Write your MySQL query statement below
select distinct l1.Num as ConsecutiveNums
from Logs l1,Logs l2,Logs l3
where l1.Id=l2.Id-1
and l2.Id=l3.Id-1
and l1.Num=l2.Num
and l2.Num=l3.Num;

image-20200727112512597

点击查看
-------------------本文结束 感谢您的阅读-------------------