gpt4 book ai didi

java - 按子数组的长度对数组进行排序

转载 作者:行者123 更新时间:2023-12-01 12:25:19 24 4
gpt4 key购买 nike

所以我有一个表示邻接列表的二维数组graph:

0:2 1 0
1:0
2:

以数组格式表示:

[[2,1,0],[0],[]]

我想要做的是按子数组(边缘列表)的长度对特定行(例如graph[0])进行排序。

在上面的示例中,排序后的图表将如下所示:

0:0 1 2
1:0
2:

[[0,1,2],[0],[]]

由于graph[0].length = 3graph[1].length = 1graph[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);
}
}

但是排序方法不接受这种格式。有人可以解释一下我做错了什么吗?

为清楚起见进行编辑:

因为上面的示例使用了数字,所以有点令人困惑,所以我将添加第二种情况:

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;
}
}

关于java - 按子数组的长度对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26397963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com