https://leetcode.com/problems/product-of-array-except-self/?envType=study-plan-v2&envId=leetcode-75
처음에는 사람이 들어올때마다, 들어온 사람의 도착 시각과, 이전 모든 사람들의 떠난 시각을 비교해서 상태를 변경해주는 식으로 코드를 짰다. (당연히 시간 초과남 ㅠㅜㅠ)
from pprint import pprint
class Solution:
def getSmallestKey(self, chairs) -> int:
false_key = [key for key, val in chairs.items() if not val]
return min(false_key)
def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:
friends_num = len(times)
times_friends = [(friends, times) for friends, times in enumerate(times)]
times_friends.sort(key=lambda x:x[1][0])
pprint(times_friends)
chairs = {}
for i in range(friends_num):
chairs[i] = False
for i in range(friends_num):
for j in range(i + 1):
if chairs[j] is not False and \
times_friends[i][1][0] >= chairs[j][1][1]:
chairs[j] = False
min_chair = self.getSmallestKey(chairs)
chairs[min_chair] = times_friends[i]
if times_friends[i][0] == targetFriend:
return min_chair
class Solution:
def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:
friends_num = len(times)
ordered_friends = sorted(range(len(times)), key=lambda x: times[x][0])
empty_chairs, occupied_chairs = list(range(len(times))), []
for i in ordered_friends:
arrive, leave = times[i]
while occupied_chairs and occupied_chairs[0][0] <= arrive:
heappush(empty_chairs, heappop(occupied_chairs)[1])
min_chair = heappop(empty_chairs)
if i == targetFriend:
return min_chair
heappush(occupied_chairs, (leave, min_chair))