[英]Sort array by length of sub arrays
所以我有一个二维数graph
,它表示一个邻接表:
0:2 1 0
1:0
2:
在多数民众赞成在阵列格式:
[[2,1,0],[0],[]]
我想要做的是根据子数组(边缘列表)的长度对特定的行 (例如graph[0]
)进行排序。
在上面的示例中,排序后的graph
如下所示:
0:0 1 2
1:0
2:
[[0,1,2],[0],[]]
由于graph[0].length = 3
和graph[1].length = 1
且graph[2].length = 0
。
我试过使用:
Arrays.sort(graph[v], new DegreeComparator(graph));
class DegreeComparator implements Comparator<Integer> {
int[][] graph;
public DegreeComparator(int[][] g) {
graph = g;
}
public int compare(Integer c1, Integer c2) {
return Integer.compare(graph[c1].length, graph[c2].length);
}
}
但是sort方法不会接受这种格式。 有人可以解释我在做什么错吗?
为清楚起见进行编辑:
因为上面的示例使用数字,所以有些混乱,因此我将添加第二种情况:
0: 4 1 2
1: 1 2 3
2:
3: 4 1
4: 0
[[4,1,2],[1,2,3],[],[4,1],[0]]
将变为(如果所有行都已排序):
0: 1 4 2 // Row 1 has more numbers than row for which has more than row 2
1: 1 3 2
2:
3: 1 4
4: 0
[[1,4,2],[1,3,2],[],[1,4],[0]]
但是,我只需要一次对一行进行排序! 不是全部。
您要求将int []与比较器进行排序
将图的类型更改为Integer [] []
class DegreeComparator implements Comparator<Integer> {
Integer[][] graph;
public DegreeComparator(Integer[][] g) {
graph = g;
}
public int compare(Integer c1, Integer c2) {
return graph[c2].length - graph[c1].length;
}
}
首先只是为了澄清您的问题:您有一个称为graph
的数组数组。 您还拥有一个引用了graph
元素的int数组(我们称其为pointers
)。 pointers
恰好是graph
的元素之一这一事实实际上并不重要。
Integer[][] graph = new Integer[4][];
Integer[] pointers = new Integer[] { 2, 1, 0, 3 };
graph[0] = pointers;
graph[1] = new Integer[] { 0 };
graph[2] = new Integer[] {};
graph[3] = new Integer[] { 1, 2 };
System.out.println(Arrays.toString(pointers));
// [2, 1, 0, 3]
final int[] lengths = new int[graph.length];
for (int i = 0; i < graph.length; i++) {
lengths[i] = graph[i].length;
}
Arrays.sort(pointers, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(lengths[o2], lengths[o1]);
}
});
System.out.println(Arrays.toString(pointers));
// [0, 3, 1, 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.