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

1
2
3
4
5
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]]


这个题目不是自己做出来的,就分享一下Discuss里面的做法:

Sort and Insert

  1. 按照h降序, k升序,把所有人排序. 排序后为:
    [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
  2. 把people按k的值,插入到idx = k的位置,原位置的people向后挪。
    1. idx = 0, 挪后结果为: [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
    2. idx = 1, 挪后结果为: [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
    3. idx = 2, 挪后结果为: [[7,0], [6,1], [7,1], [5,0], [5,2], [4,4]]
    4. idx = 3, 挪后结果为: [[5,0], [7,0], [6,1], [7,1], [5,2], [4,4]]
    5. idx = 4, 挪后结果为: [[5,0], [7,0], [5,2], [6,1], [7,1], [4,4]]
    6. idx = 5, 挪后结果为: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

代码如下:

1
2
3
4
5
6
7
8
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, (o1, o2) -> o1[0] != o2[0] ? Integer.compare(o2[0], o1[0]) : Integer.compare(o1[1], o2[1]));
ArrayList<int[]> result = new ArrayList<>();
for (int[] person : people) {
result.add(person[1], person);
}
return result.toArray(new int[result.size()][]);
}

Ref: