[LeetCode] 406. Queue Reconstruction by Height
阿新 • • 發佈:2018-12-16
題目
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) 描述,h 表示身高,k 表示排在前面的有 k 個學生的身高比他高或者和他一樣高。
思路
h降序、k 值升序,然後按排好序的順序插入佇列的第 k 個位置中。
class Solution {
public int[][] reconstructQueue(int[ ][] people) {
if(people == null || people.length == 0)
return people;
Arrays.sort(people, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o2[0]-o1[0]==0?o1[1]-o2[1]:o2[0]-o1[0];
}
} );
List<int[]> integerLst = new LinkedList<>();
for(int i = 0;i<people.length;i++){
integerLst.add(people[i][1],people[i]);
}
return integerLst.toArray(new int[people.length][]);
}
}