【LeetCode】180. 连续出现的数字

0 问题描述

html 复制代码
表:Logs

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| num         | varchar |
+-------------+---------+
在 SQL 中,id 是该表的主键。
id 是一个自增列。
 

找出所有至少连续出现三次的数字。返回的结果表中的数据可以按 任意顺序 排列。
结果格式如下面的例子所示:

 

示例 1:

输入:
Logs 表:
+----+-----+
| id | num |
+----+-----+
| 1  | 1   |
| 2  | 1   |
| 3  | 1   |
| 4  | 2   |
| 5  | 1   |
| 6  | 2   |
| 7  | 2   |
+----+-----+

输出:
Result 表:
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

解释:1 是唯一连续出现至少三次的数字。

1 数据准备

sql 复制代码
CREATE TABLE Logs  (
    `id`   int     comment '',
    `num`  string  comment ''
) COMMENT 'xxx'
    ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';

insert overwrite table Logs
values (1, '1'),
       (2, '1'),
       (3, '1'),
       (4, '2'),
       (5, '1'),
       (6, '2'),
       (7, '2');

2 思路分析

思路一:窗口函数
sql 复制代码
select
      num
from (
         select num,
                lag(num, 1, null) over (order by id )  num1,
                lead(num, 1, null) over (order by id ) num2
         from Logs
     ) tmp1
where num = num1
  and num = num2;

笔记:lag / lead 前后函数

sql 复制代码
lag(column,n,default) over(partition by xxx order by xxx) as lag_test
-- 取得column列前边的第n行数据,如果存在则返回,如果不存在,返回默认值default

lead(column,n,default) over(partition by xxx order by xxx) as lead_test

-- 取得column列后边的第n行数据,如果存在则返回,如果不存在,返回默认值default
思路二:mysql中的二元组
sql 复制代码
-- MySQL中的二元组
select 
    distinct num as consecutivenums
 from logs
 where (id+1, num) in (select * from logs)
 and (id+2, num) in (select * from logs)

思路二是参考大佬的写法。解析: (id+1, num) 括号代表二元元组,in子查询的返回结果,是由二元元组构成的表,借助【二元元组相等】代表对应元素分别相等的思路,得出上述代码逻辑;

3 总结

相关推荐
数据猿5 小时前
【金猿CIO展】上海虹迪物流科技有限公司董事长兼CIO张鹏飞:聚焦数字化核心——物流供应链的的智慧演进之路
大数据·科技
deepdata_cn6 小时前
“深数据” vs “大数据”
大数据·bigdata·深数据·deepdata
数字化转型20258 小时前
SAP Signavio 在风机制造行业的深度应用研究
大数据·运维·人工智能
sheji34169 小时前
【开题答辩全过程】以 基于大数据的城市租房数据的分析与可视化为例,包含答辩的问题和答案
大数据
Biehmltym12 小时前
【AI】09AI Agent LLM → Streaming → Session 记录 的完整链路
大数据·人工智能·elasticsearch
Data-Miner12 小时前
精品PPT | 某制造集团灯塔工厂解决方案
大数据·人工智能·制造
小湘西13 小时前
Elasticsearch 的一些默认配置上下限
java·大数据·elasticsearch
`林中水滴`14 小时前
SeaTunnel vs Flume
大数据·flume
边缘计算社区14 小时前
第12届全球边缘计算大会-精彩瞬间
大数据·人工智能·边缘计算
Zoey的笔记本14 小时前
告别“人机混战”:如何用智能管控实现安全高效协同
大数据·人工智能