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.
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]]
一开始想到先按h从小到大sort,h相等时按k从小到大sort,然后再调整每个(h, k).例如example中先sort成[[4,4], [5,0], [5,2], [6,1], [7,0], [7,1]]. 但是在调整的过程中,每次把一个元素往后移,都会影响到后面的元素,这样每个元素调整的时候都需要看前面所有的元素。
然后看到一种思路:先按h从大到小sort,h相等按k从小到大sort。换个说法,先取h最大的,按k排列好,再取倒数第二大的,按k插入,一次类推。例如example中:
1.[[7,0], [7,1]]
2.[[7,0], [6,1], [7,1]] 注:(6,1)中k=1,所以插入index=1的位置,因为保证已进入的元素都>=6
3.[[5,0], [7,0], [5,2], [6,1], [7,1]] 注:插入[5,0]到index=0,然后[5,2]到index=2,因为所有之前已进入的元素都>=5
…
public int[][] reconstructQueue(int[][] people) { Arrays.sort(people, new Comparator<int[]>(){ public int compare(int[] a, int[] b) { if (a[0] == b[0]) return a[1] - b[1]; else return b[0] - a[0]; } }); List<int[]> res = new ArrayList<int[]>(); for (int i = 0; i < people.length; i++) { int[] hk = people[i]; res.add(hk[1], hk); } return res.toArray(new int[people.length][]); }