LeetCode406 Queue Reconstruction by Height

now we are given a queue that consist of tuples, say (h, k), h stands for the height of this person and k stands for the number of person taller or equals to him who stand ahead of him.
we are given a disordered queue, and we need to restore the order as it supposed to be.
if you still not sure what all these means, then please refer to the following example:
example:
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] <— this is not the right order
Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

let’s take a minute to think about this:
I kind of confused about is there a unique solution? or multiple solutions?
if there is unique solution, then for every element, there must exist a fixed position for him.
so my idea is: Pick out tallest group of people and sort them in a subarray (S). Since there’s no other groups of people taller than them, therefore each guy’s index will be just as same as his k value.
and For 2nd tallest group (and the rest), insert each one of them into (S) by k value. So on and so forth.

based on this simple idea, we have following codes:

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people, new Comparator<int[]>(){
            @Override
            public int compare(int[] a, int[] b) {
                return a[0] == b[0] ? a[1] - b[1]: b[0] - a[0];
            }
        });
        List<int[]> list = new ArrayList<int[]>();
        for(int i = 0; i < people.length; i++) {
            list.add(people[i][1], people[i]);
        }
        
        int[][] res = new int[people.length][2];
        for (int i = 0; i < people.length; i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}
posted @ 2020-06-07 05:32  EvanMeetTheWorld  阅读(19)  评论(0)    收藏  举报