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.

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:
  1. /**
  2. * @param {number[][]} people
  3. * @return {number[][]}
  4. */
  5. var reconstructQueue = function(people) {
  6. var sorter = function (a, b) {
  7. if (a[0] != b[0]) {
  8. return b[0] - a[0]
  9. } else {
  10. return a[1] - b[1]
  11. }
  12. }
  13. people.sort(sorter);
  14. var res = [];
  15. for (let i = 0; i < people.length; i++) {
  16. res.splice(people[i][1], 0, people[i]);
  17. }
  18. return res;
  19. };
Python:
  1. class Solution(object):
  2. def reconstructQueue(self, people):
  3. """
  4. :type people: List[List[int]]
  5. :rtype: List[List[int]]
  6. """
  7. people = sorted(people, key=lambda x: x[1])
  8. people = sorted(people, key=lambda x: -x[0])
  9. res = []
  10. for p in people:
  11. res.insert(p[1], p)
  12. return res





原文地址:https://www.cnblogs.com/xiejunzhao/p/7435640.html