Queue Reconstruction by Height
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers
(h, k)
, whereh
is the height of the person andk
is the number of people in front of this person who have a height greater than or equal toh
. Write an algorithm to reconstruct the queue.Note:
The number of people is less than 1,100.
Example 1
1 | Input: |
解题思路
身高 h
最低的那些人其位置由 k
决定,因为他前面只能有 k
个不比他矮的人。身高最低的那些人站好位置后,在剩下的位置中排列剩下的人,是同样的问题,只不过每个位置的索引只包含空闲位置。
复杂度分析
- 时间复杂度:$O(n^2)$,每个人都要挑选一个与
k
对应的空闲位置。 - 空间复杂度:$O(n)$,存储结果。
代码
1 | class Solution { |