LeetCode 406. Queue Reconstruction by Height
原题链接在这里:https://leetcode.com/problems/queue-reconstruction-by-height/description/
题目:
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 当 index 把他们插入到ArrayList<int []> resList中. 然后再插第二高的,以此类推.
Time Complexity: O(n^2). n = people.length. sort用时O(nlogn), ArrayList add(index, val) takes O(n) time, and there are n items.
Space: O(n).
AC Java:
1 class Solution { 2 public int[][] reconstructQueue(int[][] people) { 3 if(people == null || people.length == 0){ 4 return people; 5 } 6 7 Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); 8 ArrayList<int []> res = new ArrayList<>(); 9 for(int [] p : people){ 10 res.add(p[1], p); 11 } 12 13 return res.toArray(new int[people.length][2]); 14 } 15 }