queue-reconstruction-by-height
https://leetcode.com/problems/queue-reconstruction-by-height/ // https://discuss.leetcode.com/topic/60394/easy-concept-with-python-c-java-solution/5 // 先按照高度从大到小排,同样高度按人数从小到大排 // 然后按照前面的人数,来进行插入 import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; public class Solution { public int[][] reconstructQueue(int[][] people) { Arrays.sort(people, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] == o2[0] ? o1[1] - o2[1] : o2[0] - o1[0]; } }); List<int[]> res = new LinkedList<>(); for (int[] cur : people) { res.add(cur[1], cur); } return res.toArray(new int[people.length][]); } /* public static void main(String[] args) { // write your code here System.out.println("Hello"); int[][] people = {{7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2}}; Main mn = new Main(); int[][] ret = mn.reconstructQueue(people); StringBuilder sb = new StringBuilder(); for (int i=0; i<ret.length; i++) { for (int j=0; j<ret[0].length; j++) { sb.append(ret[i][j]); sb.append(','); } sb.append('|'); } System.out.println(sb.toString()); } */ }
注意这一句
return res.toArray(new int[people.length][]);
经过实验,填写 (new int[][2]) 或者 (new int[][]) 都是不行的。需要在前一个下标处填写。而填写的数值范围是0到length,再大再小都不行。在这个范围内,返回的结果都是一样的。