406 Queue Reconstruction by Height
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]]
分析& 代码
来自discuss
把给的[h, k]对进行排序:
- 如果height一样,按照k的递增排
- 如果height不一样,按照height的递减排
比如,输入[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
排序完应该是这样[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]
.
整体代码的思路是:
- 先找到最高的所有对,然后按照k的顺序排,比如
[7,0], [7,1]
- 然后把次高的对,按照k的顺序放进去,
[7,0], [6,1], [7,1]
- 重复
代码是:
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if(a[0] == b[0]) {
return a[1] - b[1];
} else {
return b[0] - a[0];
}
}
});
List<int[]> list = new ArrayList<>();
for(int[] person: people) {
list.add(person[1], person);
}
return list.toArray(new int[list.size()][]);
}