LeetCode六月挑战赛6. 6
Queue Reconstruction by Height(LeetCode 406)
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为在他的前面有多少个比他身高高的人。[5,0],身高为5,在他前面没有人比他身高高或者相等,k=0,符合要求。[7,0] 在他前面没有人比他的身高高或者相等,k=0,符合要求。[5,2],身高为5,在他前面比他身高高或者相等有2个,k=2,符合要求。[6,1],身高为6,在他前面比他身高高或者相等有1个,k=1,符合要求。[4,4],身高为4,在他前面比他身高高或者相等有4个,k=4,符合要求。[7,1],身高为7,在他前面比他身高高或者相等有1个,k=1,符合要求。
思路
首先先将所有人按照身高从大到小排列, 如果身高相同,从小到大排序k。接着将排序好的数组加入到list中,位置为k,值为[h,k],因为身高已经从大到小排序,大的永远比小的先加入到result数组中,因此,k为0时,位置为0,k为1时位置为1.
代码
class Solution {
public int[][] reconstructQueue(int[][] people) {
//第一种排序方法
// Arrays.sort(people, new Comparator<int[]>(){
// public int compare(int[] a1, int[] a2){
// if(a1[0]!=a2[0]){
// return a2[0]-a1[0];
// }else{
// return a1[1]-a2[1];
// }
// }
// });
//第二种排序方法
Arrays.sort(people, (a,b) -> a[0] == b[0] ? a[1]-b[1] : b[0]-a[0]);
List<int[]> result = new ArrayList<>();
for(int i=0;i<people.length;i++){
int[] arr = people[i];
result.add(arr[1],arr);
}
int[][] res = new int[people.length][2];
for(int i=0;i<people.length;i++){
res[i]=result.get(i);
}
return res;
}
}