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

Solution

(1) Java

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        if (people == null || people.length == 0 || people[0].length == 0) {
            return people;
        }   
        Arrays.sort(people, (int[] p1, int[] p2)->{
            if (p1[0] != p2[0]) {
                return p2[0]-p1[0];
            } else {
                return p1[1]-p2[1];
            }
        });
        int[][] rst = new int[people.length][people[0].length];
        List<int[]> list = new LinkedList<>();
        for (int i = 0; i < people.length; i++) {
            int pos = people[i][1];
            list.add(pos, new int[]{people[i][0], people[i][1]});
        }
        for (int i = 0; i < people.length; i++) {
            rst[i][0] = list.get(i)[0];
            rst[i][1] = list.get(i)[1];
        }
        return rst;
    }
}

(2) Python

class Solution:
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        if not people or not people[0]:
            return people
        people.sort(key=lambda p: (-p[0], p[1]))
        rst = []
        for p in people:
            rst.insert(p[1], p)
        return rst

(3) Scala



results matching ""

    No results matching ""