[英]sorting array of arrays in descending order using arrays.sort function is resulting in errors in java
问题: https://leetcode.com/problems/maximum-units-on-a-truck/我应该对大小为 2 的 arrays 数组进行排序(例如 [[1,3],[2,2],[ 3,1]]) 根据内部元素的第二个值降序排列。 即对于第一个元素[1,3],根据值 3. ,但我的代码导致错误:没有找到适合 sort() 的方法。将不胜感激。
这是我在 java 中的代码
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
Arrays.sort(boxTypes, new Comparator<int[][]>() {
public int compare(final int[][] entry1, final int[][] entry2) {
if (entry1[0][0] < entry2[0][0])
return 1;
else return -1;
}
}
);
for (int i = 0; i < boxTypes.length; i++)
System.out.println(boxTypes[i]);
return 0;
}
}
如评论中所述,您正在按内部元素排序,即int[]
,因此您需要Comparator<int[]>
。
public class Solution {
public static void main(String[] args) {
int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
Arrays.sort(input, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[1], o1[1]);
}
});
System.out.println(Arrays.deepToString(input));
}
}
注意return Integer.compare(o2[1], o1[1]);
,第二个参数与第一个参数进行比较,以实现降序。
您也可以使用 lambda 实现相同的效果,使其更短且更具可读性。
public class Solution {
public static void main(String[] args) {
int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
System.out.println("Initial array - " + Arrays.deepToString(input));
Arrays.sort(input, (o1, o2) -> Integer.compare(o2[1], o1[1]));
System.out.println("Sorted array - " + Arrays.deepToString(input));
}
}
首先,你不能在<>
中使用原生类型,你需要使用Integer
来代替。 那么你需要比较的是内部数组Integer[]
如果我没记错的话,所以你的比较器不能工作。 在这里,您只是尝试根据第一个数组的第一个元素对 arrays 的 2 个 arrays 进行排序。
这是我要做的(使用流):
Integer[][] sortedBoxTypes = Arrays.stream(boxTypes).sorted(Comparator.comparing(entry -> entry[1])).toArray(Integer[][]::new);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.