leetcode:406. Queue Reconstruction by Height
阿新 • • 發佈:2018-12-15
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]]
題目給出一系列陣列,每個陣列代表一個人,其中每個陣列的第一個數代表這個人的身高,第二個數代表這個人前面有多少個身高高於或等於他的人;要求通過演算法將這些人安放在正確的位置上,程式碼如下:
point:為什麼要先按身高降序排,身高相等的時候再按前面的人數升序排?
1、因為按身高進行降序排列以後,從前向後遍歷排序以後的陣列(人)時,當發現位置不對的陣列(人)時,只可能是這個人前面的不比他矮的人數多於他前面應有不比他矮的人數,此時只需要把他往前移動到正確的位置即可,當將其向前移動時,由於前面的人都不比他矮,所以並不會改變之前站好位置的人的正確性。
2、由於已經按身高進行了降序排列,所以遍歷到某個陣列(人)時,很容易可以得到其前面有幾個不比他矮的人數,即遍歷index:i。
public class Solution { public int[][] reconstructQueue(int[][] people) { // 先按身高降序對陣列進行排序,如果身高一樣,則根據前面的人數按升序排 Arrays.sort(people, new Comparator<int[]>() { // 其實new介面就相當於new一個實現這個介面的匿名內部類,要new 這個匿名內部類就必須實現介面的抽象方法 // 實現抽象方法 // compare方法,返回-1:01在前,返回1,o2在前 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; } } } }); // 拍好序後遍歷,判斷是否位置正確,如不正確則往前移至正確位置(只有往前移才能到正確位置) for (int i = 0; i < people.length; i++) { // 判斷位置是否正確 if (people[i][1] != i) { dealArray(people, people[i][1], i); } } return people; } /** * 將j位上的數插入到i位上,然後陣列依次後移 ej:1-2-3-4-5-6 i=1,j=4,----> 1-5-2-3-4-6 * @param arrays * @param i * @param j */ private void dealArray(int[][] arrays, int i, int j) { int[] temp = arrays[j]; while (j > i) { arrays[j] = arrays[j - 1]; j--; } arrays[i] = temp; } }