一、问题描述
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]]
二、我的思路
没正确思路。刚开始想的是先把k是0的找出来,然后按height生序排列。然后再把k是1的找出来插空填入。然后就很麻烦了。
看了别人的思路和代码后重写了一下:
class Solution {
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, new Comparator<int[]> (){
@Override
public int compare(int[] o1, int[] o2){
if(o1[0] < o2[0]){
return 1;
}
else if(o1[0] == o2[0]){
if(o1[1] > o2[1]){
return 1;
}
else if(o1[1] < o2[1]){
return -1;
}
else{
return 0;
}
}
else{
return -1;
}
}
});
List<int[]> res = new LinkedList<>();
for(int[] cur: people){
res.add(cur[1], cur);
}
return res.toArray(new int[people.length][]);
}
}
注意sort是生序排列的。compare函数返回值注意别搞反了。。
三、淫奇技巧
1)来自:https://leetcode.com/problems/queue-reconstruction-by-height/discuss/
把h最大的找出来,按k生序排列。k即为其在新建数组里的idx,因为没人比他们大,比他们大的只有同组的;
然后把h倒数第二大的找出来,按k生序排,k即为其在新建数组里的idx....
太巧妙了吧!代码写的也好:
public class Solution {
public int[][] reconstructQueue(int[][] people) {
//pick up the tallest guy first
//when insert the next tall guy, just need to insert him into kth position
//repeat until all people are inserted into list
Arrays.sort(people,new Comparator<int[]>(){
@Override
public int compare(int[] o1, int[] o2){
return o1[0]!=o2[0]?-o1[0]+o2[0]:o1[1]-o2[1];
}
});
List<int[]> res = new LinkedList<>();
for(int[] cur : people){
res.add(cur[1],cur);
}
return res.toArray(new int[people.length][]);
}
}```
2)
四、知识点
1)Comparator & compare
return type:https://stackoverflow.com/questions/6478515/return-type-from-a-comparator
2)Linked list
五、问题
题目里给了1100是干啥的。。