1. 程式人生 > >[leetcode] 406.Queue Reconstruction by Height

[leetcode] 406.Queue Reconstruction by Height

clas 其中 發現 可能 etc index stand true eight

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;
	}
}

  

[leetcode] 406.Queue Reconstruction by Height