题目连接:https://leetcode.com/problems...app
greedy的题感受思路好难写啊。
首先确定是要排序,首先想到的思路是先按h再按k排序,h从低到高,k从高到低,缘由是第一步想先把是0的yi 个一个放进结果里,而后把前面的k都--,第二遍仍是找k = 0的。一直重复到结束。code
es: [[4, 4], [5, 2], [5, 0], [6, 1], [7, 1], [7, 0]]排序
第一遍:leetcode
result: [[5, 0], [7, 0]]get
aux: [[4, 2], [5, 0], [6, 0], [7, 0]]io
第二遍:class
result: [[5, 0], [7, 0], [5, 2], [6, 1]]List
aux: [[4, 0], [7, 0]]queue
第三遍:sort
result: [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]
aux: []
每次最前面的减的是最多的,因此考虑倒过来作:
[[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]]
这样减的时候就是碰到[7, 0]以后[7, 1], [6, 1]先减1,碰到了[5, 0],以后[5, 2], [4, 4]是减2。又因为减到0的时候要倒过来append到结果里面,实际上就是把h小的查到前面对应位置的过程。discussion给的解法实在太厉害了,真想不出来。
public class Solution { public int[][] reconstructQueue(int[][] people) { if(people.length == 0) return people; Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); List<int[]> result = new ArrayList(); for(int[] person : people) { result.add(person[1], person); } return result.toArray(new int[result.size()][2]); } }