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

相关推荐
K3v19 分钟前
【git】删除本地以及远端已经合并到master的分支
大数据·git·elasticsearch
53AI1 小时前
智能调度赋能交通行业:从经验驱动到数据智能的跨越
大数据·人工智能·知识库·智能调度·53ai
黎阳之光2 小时前
黎阳之光核工厂202应急管控平台|全域实景孪生,筑牢核安全最后一道防线
大数据·人工智能·算法·安全·数字孪生
roman_日积跬步-终至千里2 小时前
【系统架构设计师-综合题-知识点(1)】系统工程与信息技术基础
大数据
Elastic 中国社区官方博客3 小时前
Elasticsearch:快速近似 ES|QL - 第二部分
大数据·数据库·sql·elasticsearch·搜索引擎·全文检索
Cisyam^3 小时前
Bright Data Web Scraping 指南:用 MCP + Dify 自动采集 TikTok 与 LinkedIn数据
大数据·前端·人工智能
captain_AIouo3 小时前
Captain AI功能全景解析——从选品到物流的智能闭环
大数据·人工智能·经验分享·aigc
xunmaiai 8884 小时前
揭秘OZON高性价比选品:如何甄别真正靠谱的合作公司?
大数据·人工智能·python
xlq223224 小时前
43.线程同步
大数据·linux
只说证事4 小时前
CDA数据分析师适合在校生吗?什么时候准备更划算
大数据