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正好是其插入的下标值:
插入7:
[7, 0], [7, 1]
插入6
[7, 0], [6, 1], [7, 1]
.......
class Solution {
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];
return b[0] - a[0];
}
});
List<int[]> tmp = new ArrayList(people.length);
for (int[] p : people) {
tmp.add(p[1], p);
}
return tmp.toArray(new int[][]{});
}
}
也可以不使用额外空间,排序好的数组向前移动i - people[i][1]
位就是其真实位置
class Solution {
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];
return b[0] - a[0];
}
});
for (int i = 0; i < people.length; i++) {
int[] cur = people[i];
for (int j = i; j > cur[1] ; j--) {
int tmp[] = people[j];
people[j] = people[j - 1];
people[j - 1] = tmp;
}
}
return people;
}
}