# Write your MySQL query statement below
180. 连续出现的数字
表:Logs
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | num | varchar | +-------------+---------+ id 是这个表的主键。
编写一个 SQL 查询,查找所有至少连续出现三次的数字。
返回的结果表中的数据可以按 任意顺序 排列。
查询结果格式如下面的例子所示:
示例 1:
输入: Logs 表: +----+-----+ | Id | Num | +----+-----+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 1 | | 6 | 2 | | 7 | 2 | +----+-----+ 输出: Result 表: +-----------------+ | ConsecutiveNums | +-----------------+ | 1 | +-----------------+ 解释:1 是唯一连续出现至少三次的数字。
原站题解
pythondata 解法, 执行用时: 400 ms, 内存消耗: 67.1 MB, 提交时间: 2024-05-27 10:22:31
import pandas as pd def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame: if logs.empty: return pd.DataFrame(columns=['ConsecutiveNums']) # 确保 'num' 列的数据类型为整数 logs['num'] = logs['num'].astype('Int64') # 使用'Int64'类型以处理缺失值 # 创建包含所有id的完整数据框,并用0填充缺失的num值 complete_logs = pd.DataFrame({'id': range(logs['id'].max() + 1)}) complete_logs = complete_logs.merge(logs, on='id', how='left') complete_logs['num'] = complete_logs['num'].fillna(0).astype(int) # 检查相邻数字是否不相同,并为它们分配一个唯一的值以标记连续出现的数字组 complete_logs['diff'] = complete_logs['num'].ne(complete_logs['num'].shift()).cumsum() # 计算每个数字在每个分组中的出现次数 consecutive_counts = complete_logs.groupby(['num', 'diff']).size().reset_index(name='count') # 筛选出至少连续出现三次的数字 result = consecutive_counts[consecutive_counts['count'] >= 3]['num'].unique() # 创建包含连续出现至少三次的数字的数据框 result_df = pd.DataFrame({'ConsecutiveNums': result}) return result_df
pythondata 解法, 执行用时: 467 ms, 内存消耗: 66.5 MB, 提交时间: 2024-05-27 10:22:03
import pandas as pd def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame: logs = logs.sort_values('id').reset_index(drop=True) logs['num1'] = logs.iloc[1:, 1].reset_index(drop=True) logs['num2'] = logs.iloc[2:, 1].reset_index(drop=True) logs['id1'] = logs.iloc[1:, 0].reset_index(drop=True) logs['id2'] = logs.iloc[2:, 0].reset_index(drop=True) logs.dropna(inplace=True) return logs[(logs['num'] == logs['num1'])&(logs['num'] == logs['num2'])&(logs['id'] == logs['id1']-1)&(logs['id1'] == logs['id2']-1)]['num'].reset_index().rename(columns={'num':'ConsecutiveNums'})[['ConsecutiveNums']].drop_duplicates()
mysql 解法, 执行用时: 3183 ms, 内存消耗: N/A, 提交时间: 2018-08-22 15:53:58
# Write your MySQL query statement below select distinct L1.Num as ConsecutiveNums from Logs L1 left join Logs L2 on L1.id = L2.id - 1 left join Logs L3 on L2.id = L3.id - 1 where L1.Num = L2.Num and L2.Num = L3.Num;
mysql 解法, 执行用时: 3750 ms, 内存消耗: N/A, 提交时间: 2018-08-22 15:51:51
# Write your MySQL query statement below select distinct L1.Num as ConsecutiveNums from Logs L1, Logs L2, Logs L3 where L1.id = L2.id - 1 and L2.id = L3.id - 1 and L1.Num = L2.Num and L2.Num = L3.Num;