首页 > 数据库 >【LeetCode 2494. 合并在同一个大厅重叠的活动】[MySQL 用户变量/Pandas]面向过程编程解决区间合并问题

【LeetCode 2494. 合并在同一个大厅重叠的活动】[MySQL 用户变量/Pandas]面向过程编程解决区间合并问题

时间:2024-01-22 10:07:43浏览次数:45  
标签:end interval 合并 2494 Pandas day farest id hall

目录

  • 题目地址
  • MySQL代码
  • 等效pandas代码

题目地址

https://leetcode.cn/problems/merge-overlapping-events-in-the-same-hall/

MySQL代码

# Write your MySQL query statement below

with t2 as(
    select 
    *

    # ----只需要改动这里的逻辑,其他不要动。注意里面的语句是“顺序执行的”-----------

    -- 如果切换hall_id了,一些变量需要改变
    ,(case when (@prev_hall_id is null or @prev_hall_id<>hall_id) then @farest_interval_start:=start_day end)
    ,(case when (@prev_hall_id is null or @prev_hall_id<>hall_id) then @farest_interval_end:=end_day end)
    ,(case when (@prev_hall_id is null or @prev_hall_id<>hall_id) then @interval_id := @interval_id +1 end)
    

    -- 如果新区间的开始要晚于维护区间的结尾,那么开启新区间
    , (case when @farest_interval_end < start_day then @interval_id := @interval_id +1 else @interval_id end) as interval_id
    , (case when @farest_interval_end < start_day then @farest_interval_start:=start_day end)
    , (case when @farest_interval_end < start_day then @farest_interval_end:=end_day end)
    


    -- 如果新区间的开始不晚于维护区间的结尾,可能会发生区间的合并。由于我们已经按照start_day asc, end_day asc排序了。所以只可能更新@farest_interval_end
    ,(case when @farest_interval_end < start_day then "whatever" else
        (case when @farest_interval_end <= end_day then @farest_interval_end:= end_day end)
    end)
    

    , @farest_interval_start as farest_interval_start
    , @farest_interval_end as farest_interval_end
    , @prev_hall_id := hall_id

    # ----只需要改动这里的逻辑,其他不要动。注意里面的语句是“顺序执行的”-----------

    from (select * from HallEvents order by hall_id asc, start_day asc, end_day asc)  sorted_HallEvents,
    (select @prev_hall_id := null, @farest_interval_start := null, @farest_interval_end := null, @interval_id := 0) vars
)


select hall_id, farest_interval_start as start_day
, farest_interval_end as end_day 
from 
(select *,
row_number() over(partition by interval_id order by start_day desc, end_day desc) as rn
from t2) tmp1
where rn=1
order by  hall_id, start_day, end_day

等效pandas代码

import pandas as pd

def merge_events(hall_events: pd.DataFrame) -> pd.DataFrame:
    # Sort the DataFrame by hall_id, start_day, and end_day
    sorted_events = hall_events.sort_values(by=['hall_id', 'start_day', 'end_day'])
    
    # Initialize the variables
    prev_hall_id = None
    farest_interval_start = None
    farest_interval_end = None
    interval_id = 0
    intervals = []
    
    # Iterate over the rows of the sorted DataFrame
    for row in sorted_events.itertuples(index=False):
        # Check if we need to reset the variables because the hall_id has changed
        if prev_hall_id is None or prev_hall_id != row.hall_id:
            intervals.append((prev_hall_id, farest_interval_start, farest_interval_end, interval_id))
            farest_interval_start = row.start_day
            farest_interval_end = row.end_day
            interval_id += 1
        # Check if the new interval starts after the farthest interval end
        if row.start_day > farest_interval_end:
            # Append the finished interval to the list
            intervals.append((prev_hall_id, farest_interval_start, farest_interval_end, interval_id))
            # Start a new interval
            farest_interval_start = row.start_day
            farest_interval_end = row.end_day
            interval_id += 1
        # This case is when the new interval overlaps with the farthest interval end
        elif row.end_day > farest_interval_end:
            # Extend the current interval
            farest_interval_end = row.end_day
        
        prev_hall_id=row.hall_id

        print(f"{row.hall_id} {prev_hall_id} {farest_interval_start} {farest_interval_end} {row.start_day} {row.end_day}")
        
    
    # Add the last interval to the list if it exists
    if farest_interval_start is not None and farest_interval_end is not None:
        intervals.append((prev_hall_id, farest_interval_start, farest_interval_end, interval_id))
    


    # Create a DataFrame from the list of intervals
    intervals_df = pd.DataFrame(intervals, columns=['hall_id', 'start_day', 'end_day', 'interval_id'])

    
    # Select the last interval for each interval_id
    final_intervals_df = intervals_df.sort_values(by=['interval_id', 'start_day', 'end_day'], ascending=[True, False, False])
    final_intervals_df = final_intervals_df.drop_duplicates(subset='interval_id', keep='first')
    
    # Sort the final DataFrame and reset the index
    final_intervals_df = final_intervals_df.sort_values(by=['hall_id', 'start_day', 'end_day']).reset_index(drop=True)
    
    # Drop the interval_id column as it's not needed in the final output
    final_intervals_df = final_intervals_df.drop(columns='interval_id').dropna(subset=['hall_id'])
    
    return final_intervals_df



标签:end,interval,合并,2494,Pandas,day,farest,id,hall
From: https://blog.51cto.com/u_15247503/9360637

相关文章

  • 【LeetCode1747. 应该被禁止的 Leetflex 账户】[MySQL 用户变量/Pandas]面向过程编程;
    目录题目地址MySQL代码等效pandas代码题目地址https://leetcode.cn/problems/leetflex-banned-accounts/description/MySQL代码witht1as(selectaccount_id,ip_address,loginastick,"login"asmytypefromLogInfounionallselectaccount_id,ip......
  • 【LeetCode 2701. 连续递增交易】[MySQL 用户变量/Pandas]面向过程编程得到严格递增连
    目录题目地址MySQL代码等效pandas代码题目地址https://leetcode.cn/problems/consecutive-transactions-with-increasing-amounts/MySQL代码#WriteyourMySQLquerystatementbelowwitht1as(select*#--------------------------只需要改动这里的逻辑,其他......
  • 【Leetcode 2474. 购买量严格增加的客户】[MySQL 用户变量/Pandas]面向过程编程解决严
    目录题目地址MySQL代码等效pandas代码题目地址https://leetcode.cn/problems/customers-with-strictly-increasing-purchases/description/MySQL代码#WriteyourMySQLquerystatementbelowwitht1as(selectcustomer_id,year(order_date)asmy_year,sum(price)......
  • Object.assign()详解,Object.assign()与$.extend()合并对象,浅拷贝,js给现有对象增加新属
    一、简介:Object.assign()方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。简单来说,就是Object.assign()是对象的静态方法,可以用来复制对象的可枚举属性到目标对象,利用这个特性可以实现对象属性的合并。二、用法:Object.assign(target,...sour......
  • CF-570-D-启发式合并
    570-D题目大意给定一棵\(n\)个节点的树,根节点为\(1\),每个节点上有一个小写字母\(ch\)。定义节点\(x\)的深度为\(x\)到根节点的路径上的节点数量。\(q\)次询问,每次询问查询以\(x\)为根的子树之中所有深度为\(d\)的节点上字母重排之后是否可以构成一个回文串。Solution对于一组......
  • 一本通金牌导航 分治法 E.工程划分 / P5290 [十二省联考 2019] 春节十二响(启发式合并)
    题目传送门题意简述:将树上\(n\)个点划分为若干个集合,使得集合中的点两两没有祖孙关系。一个集合的权值是集合内点的权值的最大值,求所有集合的权值之和的最小值。首先这题有个非常显然的贪心:将几个权值大的点尽可能的合并到一个集合中是更优的。集合中的点两两没有祖孙关系,说......
  • 序列合并
    #include<cstdio>//引入cstdio库,用于输入输出流操作#include<queue>//引入queue库,用于使用优先队列数据结构usingnamespacestd;//使用命名空间std,以便简化代码书写inta[100005]={},b[100005]={},to[100005]={},i,n;//声明并初始化数组a、b、to和......
  • 无涯教程-PDFBox - PDF合并(Merge)
    在上一章中,无涯教程已经看到了如何将给定的PDF文档拆分为多个文档。现在学习如何将多个PDF文档合并为一个文档。合并多个PDF文档您可以使用名为PDFMergerUtility的类将多个PDF文档合并为一个PDF文档,该类提供了将两个或多个PDF文档合并为一个PDF文档的方法。以下是合并多个PD......
  • Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
    大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.to_excel之前把这一列转换成字符串,或者你在Excel上设置......
  • Git将某个文件合并到指定分支
    企业开发中,经常会单独拉分支去做自己的需求开发,但是某些时候一些公共的配置我们需要从主线pull,这时候整个分支merge显然不合适1.切换至待合并文件的分支gitcheckout<branch>2.将目标分支的单个文件合并到当前分支gitcheckout<目标分支>--<文件路径>3.提交合并后的......