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

相关推荐
ApacheSeaTunnel20 分钟前
LLM 时代,DataAgent × WhaleTunnel 如何将数据库变更瞬时 “转译” 为洞察?
大数据·ai·开源·llm·数据同步·白鲸开源·whaletunnel
凯子坚持 c1 小时前
从零开始:开发一个仓颉三方库的完整实战
大数据·elasticsearch·搜索引擎
人大博士的交易之路2 小时前
今日行情明日机会——20251104
大数据·数据挖掘·数据分析·缠论·涨停回马枪·道琼斯结构
John Song2 小时前
用zookpeer搭建Hadoop的HA集群,组件启动的启动顺序是什么?
大数据·hadoop·debian
Hello.Reader2 小时前
Flink Table API & SQL 概念、常用 API 与工程落地
大数据·sql·flink
Empty_7775 小时前
Elasticsearch+Logstash+Filebeat+Kibana部署
大数据·elasticsearch·搜索引擎
武子康5 小时前
大数据-144 Apache Kudu:实时写 + OLAP 的架构、性能与集成
大数据·后端·nosql
敲上瘾6 小时前
Elasticsearch从入门到实践:核心概念到Kibana测试与C++客户端封装
大数据·linux·c++·elasticsearch·搜索引擎·全文检索
api_180079054607 小时前
请求、认证与响应数据解析:1688 商品 API 接口深度探秘
java·大数据·开发语言·mysql·数据挖掘
0和1的舞者9 小时前
网络通信的奥秘:网络层ip与路由详解(四)
大数据·网络·计算机网络·计算机·智能路由器·计算机科学与技术