【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 总结

相关推荐
Data_Journal6 小时前
用于网页抓取的 Node-unblocker
大数据·开发语言·数据库·python·scrapy
涤生大数据6 小时前
一次“没有运行日志”的DolphinScheduler任务失败排查
大数据·数据库·人工智能·状态模式
专注API从业者6 小时前
告别人工盯品!借助 Open Claw 搭建电商商品自动化监控与数据分析系统(完整可运行源码)
大数据·运维·数据库·数据分析·自动化
多加点辣也没关系9 小时前
Git - 的安装与使用
大数据·git
醉颜凉9 小时前
Elasticsearch 相关性评分核心解密:tie_breaker 参数作用原理与实战调优全解析
大数据·elasticsearch·jenkins
芯小途20269 小时前
影视 AIGC 素材管理:改到第 108 版,为什么「块级去重」能把 TB 级素材压回百 GB(附估算脚本)
大数据·aigc
IanSkunk10 小时前
视光中心建设复盘:从流程断层到组织能力的落地路径
大数据·人工智能
fanged10 小时前
Yocto1--环境搭建和验证
大数据·搜索引擎·嵌入式
微石科技11 小时前
社区卫生中心慢病管理怎么做?宁波微石科技智慧医康系统:一个平台管住趋势、随访、患者
大数据·人工智能·科技
大大大大晴天11 小时前
K8S 在大数据里的真正价值:适用场景、收益边界与不适合的地方
大数据·云原生