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

相关推荐
Guheyunyi8 小时前
安全风险预警系统的核价值与战略意义
大数据·人工智能·科技·安全·信息可视化
云和数据.ChenGuang8 小时前
AI向量数据库chromadb的swagger-ui的运行使用教程
大数据·数据库·人工智能·ui·向量数据库·向量计算
历程里程碑8 小时前
链表--LRU缓存
大数据·数据结构·elasticsearch·链表·搜索引擎·缓存
腾视科技TENSORTEC8 小时前
腾视科技大模型一体机解决方案:低成本私有化落地,重塑行业智能应用新格局
大数据·人工智能·科技·ai·ainas
guoji77889 小时前
Gemini vs Grok镜像站技术拆解对比:视觉派与实时派的正面交锋
大数据·人工智能·gpt
乐迪信息9 小时前
乐迪信息:AI防爆摄像机在智慧港口船舶监测中的技术优势
大数据·人工智能·安全·计算机视觉·目标跟踪
合合技术团队9 小时前
合合信息联合亚马逊云科技推出长文档智能处理方案,破解智能体规模化落地困局
大数据·人工智能·科技·文档解析
尽兴-9 小时前
Elasticsearch 入门全景:核心概念与典型应用场景速览
大数据·elasticsearch·搜索引擎·全文检索·高性能·elastic stack·分布式生态
php_kevlin9 小时前
git提交限制规范
大数据·git·elasticsearch
wzl202612139 小时前
基于企微API与数据中台,构建用户分层与沉默用户召回体系
大数据·人工智能·企业微信