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

相关推荐
RFID科技的魅力4 小时前
CP300R触屏RFID打印机实测:稳定输出超可靠
大数据·物联网·rfid
꧁꫞静芽꫞꧂7 小时前
【FISHER 阀门定位器工作原理、保养维护与故障处理全指南】
大数据
TDengine (老段)8 小时前
TDengine IDMP 可视化 —— 面板
大数据·数据库·人工智能·物联网·ai·时序数据库·tdengine
newsxun8 小时前
中创汇联双城峰会圆满举办 多维赋能实体高质量发展
大数据·人工智能
HcreateLabelView9 小时前
引领RFID电子标签打印新时代,打造标识打印系统新标杆
大数据·人工智能
数智化管理手记10 小时前
精益生产合理化建议核心解读:本质、价值与提报规范
大数据·网络·人工智能·低代码·制造
LaughingZhu10 小时前
移动端 AI 的价值重估:设备端智能的拐点
大数据·人工智能·经验分享·搜索引擎·语音识别
@insist12311 小时前
网络工程师-WLAN 无线局域网全解析
大数据·网络·网络工程师·软考·软件水平考试
airuike12312 小时前
以微见著,精准护航:MEMS IMU助力高铁轨道智能检测
大数据·人工智能·科技
青稞社区.13 小时前
Claude Code 源码深度解析:运行机制与 Memory 模块详解
大数据·人工智能·elasticsearch·搜索引擎·agi