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

相关推荐
Tigerbot42 分钟前
虎博科技CEO卢鑫:GEO方法论提出者,AI Marketing 与 AI GEO专家
大数据·人工智能·科技
alxraves1 小时前
医疗器械质量管理体系信息系统的详细设计
大数据·安全·健康医疗·制造
xcbrand2 小时前
快消品品牌策划公司哪家好
大数据·人工智能·python
T06205142 小时前
【实证分析】上市公司企业交易成本数据集-含代码(2000-2024年)
大数据
智慧景区与市集主理人3 小时前
露营设备租赁低效?巨有科技计时租赁系统激活五一增收新动能
大数据·人工智能
@土豆3 小时前
Elasticsearch 9.0.1 集群部署(Docker Compose + k8s 部署方式)
大数据·elasticsearch·docker
醉颜凉3 小时前
Elasticsearch 生产级核心原理:Shard Allocation Awareness 工作机制与实战配置详解
大数据·elasticsearch·搜索引擎
Lisonseekpan3 小时前
Git:如何将一个分支的特定提交合并到另一个分支?
java·大数据·git·后端·elasticsearch
财迅通Ai3 小时前
煌上煌2025年净利润大增102.32% 2026年一季度开局稳健
大数据·煌上煌
Elastic 中国社区官方博客3 小时前
使用 EDOT Browser 和 Kibana 进行 OpenTelemetry 浏览器端埋点
大数据·服务器·数据库·elasticsearch·搜索引擎·单元测试·可用性测试