二元数组的一些操作

今天是在做一道算法题,思维上没想全,最后看题解那个代码也没想到。

算法

1
根据身高重建队列

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) 根据数组第二元素付过去

如图

image-20200322233031273

image-20200322233106423

image-20200322233135719

image-20200322233147447

image-20200322233202023

image-20200322233216487

牛逼


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!