Suppose you has a random list of people standing in a queue. Each person was described by a pair of integers (h, k) , where was the height of the person and is the number of h k PE Ople in front of the WHO has a height greater than or equal to h . Write a algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
Example
input:[[7,0], [bis], [7,1], [5,0], [6,1], [5,2]]output:[[5,0], [7,0], [5,2], [6,1], [bis], [7,1]]
The topic gives a series of arrays, each of which represents a person, where the first number of each array represents the height of the person, and the second number represents the number of people in front of the person who is taller or equal to him; Ask the algorithm to put these people in the correct position, the code is as follows:
Point: Why do you first rank in descending order of height, and then the ascending number of people in the same height?
1, because in descending order of height, when the array (person) that is the wrong position is found, it is only possible that the person in front of him is not shorter than the number of people in front of him, and only need to move him forward to the correct position. Because the front of the people are not shorter than him, so it will not change the position of the right-standing people's correctness.
2, because has been in descending order by height, so traversing to an array (people), it is easy to get a few of them before the number of short, that is, traverse index:i.
public class Solution {public int[][] Reconstructqueue (int[][] people) {/////////Sort by height in descending order, if same height, According to the previous number of people in ascending order Arrays.sort (people, new comparator<int[]> () {//actually the new interface is equivalent to the new one to implement this interface anonymous inner class, to new This anonymous inner class must implement an abstract method of the interface//Implement abstract method//Compare method, return -1:01 before, return 1,o2 in front of public int compare (int[] O1, int[] O2) {if (o1[0] > O2[0]) { return-1;} else if (O1[0] < o2[0]) {return 1;} else {if (o1[1] < o2[1]) {return-1;} else {return 1;}}}); /after the sequential traversal, to determine whether the position is correct, if not correct forward to the correct position (only move forward to the correct position) for (int i = 0; i < people.length; i++) {//Determine if position is correct if (people[i][1]! = i) {Dealarray (People, people[i][1], i);}} return people;} /** * Inserts the number on the J-bit into the I-bit, then the array moves back ej:1-2-3-4-5-6 i=1,j=4,----> 1-5-2-3-4-6 * @param arrays * @param i * @param j */private Vo ID Dealarray (int[][] arrays, int i, int j) {int[] temp = Arrays[j];while (J > i) {arrays[j] = arrays[j-1];j--;} Arrays[i] = temp;}}
[Leetcode] 406.Queue reconstruction by Height