[LeetCode] 406. (sorted after insertion) to the height of the reconstruction queue ☆☆☆

 

description

Suppose scrambled group of people standing in a queue. Each person is represented by a pair of integers (h, k), where h is the person's height, k is the row in front of the person and the height h is greater than or equal to the number. Write an algorithm to reconstruct the queue.

Note:
The total number fewer than 1,100 people.

Examples

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

Resolve

First sorting insert.

According to a second row if the order of the elements: 507061715244, if achieve the object, need a lot of data comparison, exchange.

If the reverse discharge in accordance with the first element: 707161505244, if achieve the object, only need to specify the insertion location.

Code

public static int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {return o1[0] == o2[0] ? o1[1] - o2[1] : o2[0] - o1[0];
            }
        });
        List<int[]> list = new LinkedList<>();
        for (int[] p : people) {
            list.add(p[1], p);
        }return list.toArray(new int[list.size()][2]);
    }

 

Guess you like

Origin www.cnblogs.com/fanguangdexiaoyuer/p/12092961.html