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,0],[7,1][6,1][5,0][5,2][4,4]
接下来要调整整个队列,从第二个开始,
1)如[7,1] 允许比其大的一个数在其前面,那么[7,1]的位置可以不变
调整完后
[7,0],[7,1][6,1][5,0][5,2][4,4]
2)调整[6,1], 允许一个大于或者等于6的数在前面,那么就将[6,1]
插入到索引为1的地方
[7,0],[6,1][7,1][5,0][5,2][4,4]
3)调整[5,0],允许0个大于或者等于5的数在前面,将[5,0]插入在索引为0的地方
[5,0][7,0],[6,1][7,1][5,2][4,4]
4)调整[5,2],允许2个大于或者等于5的数在前面,将[5,2]插入在索引为2的地方
[5,0][7,0],[5,2][6,1][7,1][4,4]
5)调整[4,4],可允许4个大于或者等于4的数在前面,将[4,4]插入在索引为4的地方
[5,0][7,0],[5,2][6,1][4,4][7,1]
最后即为最后的结果。
总结:先按照高度从大到小的排序,就是保证在调整某个people的时候,前面的高度都是比自己高的,将自己插入到高度比自己高的人前面的时候,对前面的人也不会产生太大的影响,前面的人不会被自己挡住。
代码:
public class Solution {
public int[][] reconstructQueue(int[][] people) {
int m = people.length;
if(m==0)
return people;
int n = people[0].length;
if(n!=2)
return null;
Arrays.sort(people,new Comparator<int[]>(){
public int compare(int[] obj1,int[] obj2)
{
if(obj1[0]==obj2[0])
{
return obj1[1]-obj2[1];
}else
{
return obj2[0]-obj1[0];
}
}
});
for(int i=1;i<m;i++)
{
int temp0 = people[i][0];
int temp1 = people[i][1];
if(temp1==i) continue;
int j=i;
for(;j>temp1;j--)
{
people[j][0]=people[j-1][0];
people[j][1]=people[j-1][1];
}
people[temp1][0]=temp0;
people[temp1][1]=temp1;
}
return people;
}
}