406. Queue Reconstruction by Height

https://leetcode.com/problems/queue-reconstruction-by-height/

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]]

Thoughts

给由整数对(h, k)组成的数组,ki表示在原数组中h>=hi并排在前面的元素个数,让还原原数组。因为k是排在前面且大于h的数,按照h从大到小排序,并且同一h的k小的排前面。新建列表,按照顺序把pair(h, k)插入k位置,也就满足了它前面有k个>=h元素;后面的元素即使插在它前面,根据排序顺序也不会比h大,不会影响k的正确。

Code

class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        people, res = sorted(people, reverse=True, key=lambda x: (x[0], -x[1])), []
        for p in people:
            res.insert(p[1], p)
        return res
class Solution {
    public int[][] reconstructQueue(int[][] people) {
        List<int[]> res = new ArrayList<>();
        Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]);
        for (int[] p : people) {
            res.add(p[1], p);
        }

        return res.toArray(new int[0][0]);
    }
}

Analysis

时间复杂度O(NlgN).

Last updated