今天是在做一道算法题,思维上没想全,最后看题解那个代码也没想到。
算法
https://leetcode-cn.com/problems/queue-reconstruction-by-height/solution/gen-ju-shen-gao-zhong-jian-dui-lie-by-leetcode/
将二元数组进行排序
数组结构
1
| int[][] gas={ {7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2} };
|
根据数组的子数组的第一个元素进行降序 第二个元素升序
1 2 3 4 5 6
| 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]; } });;
|
根据第一个第二个升序
1 2 3 4 5 6 7
| Arrays.sort(people, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] == o2[0] ? o1[1] - o2[1] : o1[0] - o2[0]; } });;
|
降序
1 2 3 4 5 6
| Arrays.sort(people, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] == o2[0] ? o2[1] - o1[1] : o2[0] - o1[0]; } });;
|
这是这道算法题里面的一个步骤 具体可以先看看这个算法题
原数组int[][] gas={ {7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2} }
使用了Arrays.sort 对二元数组第一个元素降序 第二个元素升序后
得到 int[][] gas={ {7,0}, {7,1}, {6,1}, {5,0}, {5,2}, {4,4} }
使用list轮询对数组进行处理
1 2 3 4
| List<int[]> arraylist=new LinkedList<int[]>(); for(int[] p : gas){ arraylist.add(p[1], p); }
|
得到 int[][] gas={ {5,0}, {7,0}, {5,2}, {6,1}, {4,4}, {7,1} };
非常有趣 调试一看
int[][] gas={ {7,0}, {7,1}, {6,1}, {5,0}, {5,2}, {4,4} };
轮询到 {6,1}
时
这个list内部为 0=7,0 1=7,1
,执行add后结果为0=7,0 1=6,1 2=7,1
因为此时数组是个降序状态 按这个 add(index,element) 根据数组第二元素付过去
如图






牛逼