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]]
题意: 这道题是排序。告诉你每个人的身高以及这个人前面有多少比自己高的,标记为 $k$。 首先我们可以按身高从高到矮排序。 这样做的好处是,如果我们先放置高个子的人,之后相对矮的人不管站在何处都不会对其有任何影响。 如果,有人身高相同的话。那我们需要按照 $k$ 从小到大的顺序。 排完序之后,可以像插入排序一样把人依次排到相应的位置 $k$ 上。
代码
class Solution {
public int[][] reconstructQueue(int[][] people) {
if(people.length==0)
return people;
Arrays.sort(people, (a,b)->a[0]!=b[0]?b[0]-a[0]:a[1]-b[1]);
List<int[]> q = new ArrayList<>();
for(int[] p:people)
q.add(p[1], p);
return q.toArray(new int[people.length][people[0].length]);
}
}