- Today
- Total
작심삼일
[LeetCode] 406 | Queue Reconstruction by Height | Python 본문
문제 링크: https://leetcode.com/problems/queue-reconstruction-by-height/
문제
You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi.
Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).
조건
- 1 <= people.length <= 2000
- 0 <= hi <= 106
- 0 <= ki < people.length
- It is guaranteed that the queue can be reconstructed.
내 풀이
사람을 키가 작은 순으로 정렬한다.
정답으로 리턴할 ans의 원소를 [h, k]라 할 때, h를 max로 둔다.
현재 사람을 [h, k]라 할 때, 앞에 k명 만큼 큰 사람을 두는 pos를 찾는다.(첫번째 while 문)
해당하는 pos를 찾으면 ans에 비어있는 자리를 찾아서 넣는다.(두번째 while 문)
코드
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort()
ans = [[1000001, -1] for _ in range(len(people))]
for h, k in people:
num_taller, pos = 0, 0
while num_taller < k:
if ans[pos][0] >= h:
num_taller += 1
pos += 1
while ans[pos][1] != -1:
pos += 1
ans[pos] = [h, k]
return ans
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 135 | Candy | Python (0) | 2022.07.04 |
---|---|
[LeetCode] 1710 | Maximum Units on an Truck | Python (0) | 2022.07.01 |
[LeetCode] 1647 | Minimum Deletions to Make Character Frequencies Unique | Python (0) | 2022.06.28 |
[LeetCode] 1689 | Partitioning Into Minimum Number of Deci-Binary Numbers | Python (0) | 2022.06.27 |
[630] 630 | Course Schedule III | Python (0) | 2022.06.23 |