406. Queue Reconstruction by Height
- Total Accepted: 20652
- Total Submissions: 37699
- Difficulty: Medium
- Contributor: LeetCode
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k)
, where h
is the height of the person and k
is the number of people in front of this person who have a height greater than or equal to h
. Write an algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
Example:
Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
题解:研究题目之后发现这题实际上是一个变相的排序,把本来乱序的序列变成符合题目要求的顺序。正常的比较大小来排序的方法不是很适用,观察到k代表的是前面大于等于这个数的个数,那么如果先按h来从大到小排序,每一步把相同h的几个人直接按照k作为下标插入到新的序列中,即可得到符合题目要求的序列。原因是只有h比当前大的人才会影响到k,在所有比当前h大的人已经排好序的情况下插入当前的人,这个相对的位置是不会因为后面h小于当前的人进来而改变的,也不会影响到k。代码如下: