406. 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), 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.
Example12345Input:[[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]]
这个题目不是自己做出来的,就分享一下Discuss里面的做法:
Sort and Insert
- 按照h降序, k升序,把所有人排序. 排序后为:
[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
- 把people按k的值,插入到idx = k的位置,原位置的people向后挪。
- idx = 0, 挪后结果为:
[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
- idx = 1, 挪后结果为:
[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
- idx = 2, 挪后结果为:
[[7,0], [6,1], [7,1], [5,0], [5,2], [4,4]]
- idx = 3, 挪后结果为:
[[5,0], [7,0], [6,1], [7,1], [5,2], [4,4]]
- idx = 4, 挪后结果为:
[[5,0], [7,0], [5,2], [6,1], [7,1], [4,4]]
- idx = 5, 挪后结果为:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
- idx = 0, 挪后结果为:
代码如下:
|
|
Ref: