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]]给定一个二维数组,每个元素的第一位代表高度,第二位代表在经过排队序列化之后在它前面不比他低的高度数,
贪心算法:
非常奇妙按照第一位的高度由高到低排序,如果第一位相等则按照第二位的由小到大排序;
如上例排完顺序之后变成 [7,0],[7,1][6,1][5,0][5,2][4,4]
开始排序,遍历这个二维数组,将二维数组中元素的第二位作为下表插入list中,可以保证在之前插入list中的元素都比现在的元素大,那么现在插入元素之前有几个比它大的数就差在第几位,比如在插入[6,1]时(现有list是[[7,10],[7,1]]),说明在[6,1]之前只有一个元素比6大,比6大的元素一共有2个已经在list中按序排好,那么[6,1] u就只需要 插到list中索引为1的位置 这样在他前面就只有1个比它大的元素,其后的元素(相等的)一定不会排在它前面,小于的不会影响它的第二个值(1)
重点的是要学会写这种comparator的接口 实现对二维数组的排序
public class Solution {
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people,new Comparator<int[]>(){
@Override
public int compare(int[] o1, int[] o2){
//compare 1-2 升序排列 2-1 降序排列
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][]);
}
}