【解题思路】
先对people进行排序,排序按照第一个数字的大小,从小到大排序,如果第一个数字相同,则按照第二个数字从小到大的顺序排序。
对于排好序的people[ ][ ]依次取出每一个数组,对于数组people[i],他前面有people[i][1]个比他个子高的人(他的身高为people[i][0]),所以需要从头数出people[i][1] - Num(比他高的人数)个空位,然后将他插入。
需要注意的是,有一个测试样例中,有身高为0的数据。
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];
else return a[0]-b[0];
}
});
int n = people.length;
int[][] queue = new int[n][2];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < 2; j++)
{
queue[i][j] = -1;
}
}
for(int i = 0; i < n; i++)
{
int cnt = 0;
int j = 0;
while(cnt < people[i][1])
{
if(queue[j][0] == -1 && queue[j][1] == -1) cnt++;
else if(queue[j][0] >= people[i][0]) cnt++;
j++;
}
if(queue[j][0] == -1 && queue[j][1] == -1)
{
queue[j][0] = people[i][0];
queue[j][1] = people[i][1];
}
else{
int k = j+1;
while(!(queue[k][0] == -1 && queue[k][1] == -1))
{
k++;
}
queue[k][0] = people[i][0];
queue[k][1] = people[i][1];
}
}
return queue;
}
}