406. Queue Reconstruction by Height (Medium)

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

Solutions

class Solution {

    // This problem is difficult and tricky, not easy to get over it on my own. So the best option is to
    // memorize the problem-solving idea and steps.

    public int[][] reconstructQueue(int[][] people) {
        if (people == null || people.length == 0 || people[0].length == 0)
            return new int[0][0];

        Arrays.sort(people, (a, b) -> {
            if (b[0] == a[0]) {
                // Same height, adopt ascending order by prior people
                return a[1] - b[1];
            }

            // Descending order by people's height
            return b[0] - a[0];
        });

        ArrayList<int[]> tmp = new ArrayList<>();

        // Of same prior people, higher people must be situated after lower one, or else the lower
        // one will has more prior in front of him than the higher, which brings about discrepancy against
        // the given situation.

        // In light of above rule, the pre-placed element on specific slot will be edge off by later people
        // who comes with lower height and maintain the order without going against the given situation.
        int len = people.length;
        for (int i = 0; i < len; i++) {
            tmp.add(people[i][1], new int[]{people[i][0], people[i][1]});
        }

        int[][] ans = new int[people.length][2];
        int i = 0;
        for (int[] k : tmp) {
            ans[i][0] = k[0];
            ans[i++][1] = k[1];
        }

        return ans;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:17

results matching ""

    No results matching ""