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]]
解法
对二维数组people进行排序,排序规则为:先按照身高降序排序,如果身高相同则按照第二个数(前面有几个人的个数)升序进行排序,然后再按照第二个数的位置进行插入list列表中,完成之后再复制到新的数组中。
// @author: taotao @date: 17/3/30
public class Solution {
public int[][] reconstructQueue(int[][] people) {
if (people.length == 0 || people == null) {
return people;
}
if (people[0].length == 0 || people[0] == null) {
return people;
}
int[][] ret = new int[people.length][2];
Arrays.sort(people, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] == o2[0]) {
return o1[1] - o2[1];
} else {
return o2[0] - o1[0];
}
}
});
List<int[]> temp = new ArrayList<>();
for (int i = 0; i < people.length; i++) {
temp.add(people[i][1], people[i]);
}
for (int i = 0; i < people.length; i++) {
ret[i] = temp.get(i);
}
return ret;
}
}