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]]
假设你有一个随机的人员排队队列。每个人由一对整数(h,k)描述,其中h是人的高度,k是具有高度大于或等于h的这个人面前的人数。编写一个重构队列的算法。
注意: 人数小于1100。
Javascript:
/**
* @param {number[][]} people
* @return {number[][]}
*/
var reconstructQueue = function(people) {
var sorter = function (a, b) {
if (a[0] != b[0]) {
return b[0] - a[0]
} else {
return a[1] - b[1]
}
}
people.sort(sorter);
var res = [];
for (let i = 0; i < people.length; i++) {
res.splice(people[i][1], 0, people[i]);
}
return res;
};
Python:
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
people = sorted(people, key=lambda x: x[1])
people = sorted(people, key=lambda x: -x[0])
res = []
for p in people:
res.insert(p[1], p)
return res