Algorithm 如何:给定酒店和访客的入住/退房时间,找到所需的最少房间数

Algorithm 如何:给定酒店和访客的入住/退房时间,找到所需的最少房间数,algorithm,Algorithm,假设我得到一个作为(签入,签出)传入的未排序元组列表,我需要返回所需的最小房间数,以避免冲突。 到目前为止,我想: sort by checkout time room = 1 for each checkout time if there exists checkout time < checkin room += 1 end if end for return room 按签出时间排序 房间=1 每次结账时 如果存在签出时间

假设我得到一个作为(签入,签出)传入的未排序元组列表,我需要返回所需的最小房间数,以避免冲突。 到目前为止,我想:

 sort by checkout time
 room = 1 
 for each checkout time
    if there exists checkout time < checkin 
        room += 1
    end if 
 end for
 return room
按签出时间排序
房间=1
每次结账时
如果存在签出时间<签入
房间+=1
如果结束
结束
休息室
排序采用nlgn+运行时间(n),相当于O(nlgn) 我能做得更好吗?我想我可能有一些我没有处理的角落案例,但我想不出有什么


这是一个面试问题。有什么帮助吗

你的算法坏了。正确的做法是列出事件列表,然后先按时间排序,然后在签入之前签出。现在我们做如下工作:

max_rooms = 0
rooms = 0
for each event
    if event.type == checkin
        rooms += 1
        if max_rooms < rooms
            max_rooms = rooms
        end if
    else
        rooms -= 1
    end if
end for
return max_rooms
最大房间数=0
房间=0
每项活动
如果event.type==签入
房间+=1间
如果最大房间数<房间数
最大房间数=房间数
如果结束
其他的
房间-=1间
如果结束
结束
返回max_房间

您的算法已损坏。正确的做法是列出事件列表,然后先按时间排序,然后在签入之前签出。现在我们做如下工作:

max_rooms = 0
rooms = 0
for each event
    if event.type == checkin
        rooms += 1
        if max_rooms < rooms
            max_rooms = rooms
        end if
    else
        rooms -= 1
    end if
end for
return max_rooms
最大房间数=0
房间=0
每项活动
如果event.type==签入
房间+=1间
如果最大房间数<房间数
最大房间数=房间数
如果结束
其他的
房间-=1间
如果结束
结束
返回max_房间
O(nlgn)是最佳时间。但我怀疑你的算法是否给出了正确的结果。你查过一些例子了吗?该行如何工作:
如果存在签出时间
?O(nlgn)是最佳时间。但我怀疑你的算法是否给出了正确的结果。你查过一些例子了吗?该行如何工作:
如果存在签出时间