【刷题】【力扣】【180】【中等】连续出现的数字

文章目录

    • @[toc]
  • 题目描述
  • 示例
    • 输入
    • 输出
    • 解释
  • MySQL实现
    • 方法1
    • 方法2
  • Pandas实现

题目描述


  • 表:Logs
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| num         | varchar |
+-------------+---------+
在 SQL 中, id 是该表的主键
id 是一个自增列
  • 找出所有至少连续出现三次的数字
  • 返回的结果表中的数据可以按任意顺序排列

示例


输入

  • Logs
+----+-----+
| id | num |
+----+-----+
| 1  | 1   |
| 2  | 1   |
| 3  | 1   |
| 4  | 2   |
| 5  | 1   |
| 6  | 2   |
| 7  | 2   |
+----+-----+

输出

+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

解释

  • 1 1 1是唯一连续出现至少三次的数字

MySQL实现


方法1

select distinct num as ConsecutiveNums
from (select *, lead(rn, 2) over (partition by num order by rn) as rn_lead
      from (select num, row_number() over () as rn from Logs) t1) t2
where rn_lead - rn = 2;

方法2

select distinct num as ConsecutiveNums
from (select num,
             row_number() over ()                             as rn1,
             row_number() over (partition by num order by id) as rn2
      from Logs
      order by num, id) t
group by num, rn1 - rn2
having count(rn1 - rn2) >= 3;

Pandas实现


# -*- coding: utf-8 -*-
# @Time     : 2025/1/12 1:30
# @Author   : 从心
# @File     : 180.py
# @Software : PyCharm

import pandas as pd


def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame:
    if logs.empty:
        return pd.DataFrame(columns=['ConsecutiveNums'])

    logs['rn'] = logs.reset_index(drop=True).index + 1

    grouped = logs.groupby('num')
    result = []
    for name, group in grouped:
        group = group.copy()
        group['rn_lead'] = group['rn'].shift(-2)
        result.append(group)

    df = pd.concat(result)
    df = df[df['rn_lead'] - df['rn'] == 2]

    return df['num'].drop_duplicates().to_frame(name='ConsecutiveNums')

你可能感兴趣的:(#,力扣,刷题,力扣)