【问题标题】:sorting array of arrays in descending order using arrays.sort function is resulting in errors in java使用arrays.sort函数按降序对数组进行排序会导致java中的错误
【发布时间】:2022-02-02 09:48:27
【问题描述】:

问题:https://leetcode.com/problems/maximum-units-on-a-truck/ 我应该根据内部元素的第二个值按降序对大小为 2 的数组进行排序(例如 [[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[][] 进行排序时,您的比较器应该比较该数组的元素。那些类型为int[],而不是int[][]。如果两个条目相等,您还应该考虑返回 0,否则您的排序充其量是不可预测的,甚至会因异常而失败。

标签: java arrays sorting comparator greedy


【解决方案1】:

正如cmets中提到的,你是按内部元素排序的,即int[],所以你需要Comparator&lt;int[]&gt;

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

【讨论】:

  • 非常感谢您的帮助!但是我不明白为什么需要 deeptostring 函数来打印数组?
  • @smit Arrays.toString() 将以这种格式打印数组 - [[I@b4c966a, [I@2f4d3709, [I@4e50df2e]。每个元素都是int[],但数组没有toString() 覆盖,因此元素将使用默认行为进行字符串化。
  • 知道了。谢谢!
【解决方案2】:

首先,&lt;&gt; 中不能使用原生类型,需要使用 Integer 代替。那么你需要比较的是内部数组Integer[],如果我没记错的话,那么你的比较器就不能工作了。在这里,您只是尝试根据第一个数组的第一个元素对 2 个数组数组进行排序。

这是我要做的(使用流):

Integer[][] sortedBoxTypes = Arrays.stream(boxTypes).sorted(Comparator.comparing(entry -> entry[1])).toArray(Integer[][]::new);

【讨论】:

  • you can't use native type in &lt;&gt;, you need to use Integer instead - 这是错误的。您可以将原始数组用作泛型类型。 Comparator&lt;int[]&gt; 是一个有效的声明。还有一个问题是关于使用Arrays.sort() 进行排序,而不是流。
  • 好吧,我对原生类型的错误:抱歉。 Stream 只是另一种方式,当然我使用的比较器也可以在没有流的情况下使用:Arrays.sort(input, Comparator.comparing(entry -&gt; entry[1]));
猜你喜欢
  • 2012-11-12
  • 2011-02-09
  • 2019-10-18
  • 2013-09-21
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 2013-09-20
  • 1970-01-01
相关资源
最近更新 更多