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]]
t
题目大意:给定数对(i,j),i代表此人的身高,j代表此人前面有多少身高和他一样或者比他高的人的个数,要求把这些数对给排成队伍原来的顺序。
主要思路是,先对i进行升序排序,如果i相同,则对j进行降序排序,最后用个二维数组存放正确顺序。存放的顺序如下:根据j把数对插入到ans数组下标为j的位置中,如果该数据已经有元素了,则把该位置以及后面的数对全都往后挪一个位置,然后放下当前数对。因为前面我们已经根据身高降序插入,后面插入的数对不会影响到前面数对的j的值产生影响。
代码如下:
class Solution {
public int[][] reconstructQueue(int[][] people) {
for(int i=0;i<people.length;i++) {
for(int j=i+1;j<people.length;j++) {
if(people[i][0]<people[j][0]) {
exchange(people,i,j);
}
else if(people[i][0]==people[j][0]) {
if(people[i][1]>people[j][1]) {
exchange(people,i,j);
}
}
}
}
int[][] ans=new int[people.length][2];
for(int i=0;i<people.length;i++) {
if(ans[people[i][1]][0]==0) {
ans[people[i][1]][0]=people[i][0];
ans[people[i][1]][1]=people[i][1];
}
else {
for(int j=people.length-2;j>=people[i][1];j--) {
exchange(ans,j,j+1);
}
ans[people[i][1]][0]=people[i][0];
ans[people[i][1]][1]=people[i][1];
}
}
return ans;
}
void exchange(int[][] people,int i,int j) {
int temp=people[i][0];people[i][0]=people[j][0];people[j][0]=temp;
temp=people[i][1];people[i][1]=people[j][1];people[j][1]=temp;
}
}
估计是排序这里花的时间多了点。晚点想下怎么用容器来解决这个问题