파이썬 알고리즘 인터뷰 79번(리트코드 406번) Queue Reconstruction by Height
https://leetcode.com/problems/queue-reconstruction-by-height/
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key = lambda x: (x[0], -x[1]), reverse = True)
result = [0] * len(people)
while people:
height, front = people.pop()
idx = 0
temp = front
while temp > 0:
if result[idx] == 0:
temp -= 1
idx += 1
while result[idx] != 0:
idx += 1
result[idx] = [height, front]
return result
.pop()하면 키가 작은 사람부터 나온다.[height, front]라면 front의 값이 비어있는 자리 중 그 사람의 위치이다. 그러니까 front=4이면 비어있는 자리 중 4번째 자리에 들어가면 된다.front 번째 자리에 들어가면 된다.class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
output=[]
people.sort(key=lambda x: (-x[0], x[1]))
for a in people:
output.insert(a[1], a)
return output
insert메소드를 사용하는 것이 직접 자리를 찾는 것보다 빠르다.(빠른 C언어로 메소드가 구성되어 있다.)class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
heap = []
result = []
for person in people:
heapq.heappush(heap, (-person[0], person[1]))
while heap:
person = heapq.heappop(heap)
result.insert(person[1], [-person[0], person[1]])
return result
insert는 써본 적이 없었는데 알아두어야겠다.