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]]
思路1:每次挑选k为0的,且为最小的数组。即挑选[5,0],随后对所有数值进行更新,如果挑选数组h的值比当前值大,则当前数组的k--。repeat直至队列为空。O(n^2)
public int[][] reconstructQueue(int[][] people) {
int m = people.length;
int[][] temp = new int[m][2];
for(int i = 0;i<m;i++){temp[i][0] = people[i][0];temp[i][1] = people[i][1];}
int[][] result = new int[m][2];
for(int i = 0;i<m;i++)
{
int min = Integer.MAX_VALUE;
int k = 0;
for(int j=0;j<m;j++)
{
if(people[j][1] == 0 && people[j][0] < min)
{
min = people[j][0];
k = j;
}
}
for(int j=0;j<m;j++)
{
if(people[j][0] <= people[k][0])
{
people[j][1]--;
}
}
result[i] = temp[k];
}
return result;
}
思路2:
对队列进行排序,排序方式是按h值从大到小排序,如果h相同则按k值从小到大排序。排好序后,依次将队列中数组插入到k位置的队列M中,这样既不会影响其在M后面的数组,自身也会满足条件。
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
// TODO Auto-generated method stub
return o1[0] != o2[0] ? o2[0] - o1[0] : o1[1] - o2[1];
}
});
for(int i = 0;i<people.length;i++)
{
System.out.println(people[i][0]+","+people[i][1]);
}
List<int[]> re = new ArrayList<int[]>();
for(int[] cur : people)
{
re.add(cur[1], cur);
}
return re.toArray(new int[people.length][2]);
}