【问题标题】:Sorting a 2d matrix first by X and then by Y [closed]首先按 X 排序 2d 矩阵,然后按 Y [关闭]
【发布时间】:2021-08-04 05:42:45
【问题描述】:
int[][] points = new int[n][2];
..
//sort by x values and then y if x's are the same
Arrays.sort(points, (a, b) -> a[0] - b[0] == 0 ? a[1] - b[1] : a[0] - b[0]);

这是最佳解决方案吗?我刚刚在我的 IDE 中用一些随机数对其进行了测试,它似乎有效。

【问题讨论】:

    标签: java arrays sorting matrix multidimensional-array


    【解决方案1】:

    与其他解决方案相比是否最佳?您正在对二维数组进行排序并提供一个比较器来管理排序。 Arrays.sort 实现了一种高效、稳定的排序算法。我会使用它,但我会指定比较器如下:

    Arrays.sort(points, Comparator.comparingInt((int[] a) -> a[0])
                .thenComparingInt(a -> a[1]));
    

    减去元素以符合比较器的要求不是一个好的做法,当值接近 Integer.MAX_VALUEInteger.MIN_VALUE 时,可能会导致数据结构排序不正确。

    【讨论】:

    • 感谢您告诉我。我不知道 compareInt 是存在的。我们是否也可以使用 Integer.compareTo 来避免溢出?
    • Integer compareTo 比较像obj1.compareTo(obj2) 这样的两个整数对象,这对原语不起作用。但是你可以做 Integer.compare(a,b) 其中 a 和 b 是整数。事实上,Comparator.comparingInt 就是这么用的。
    【解决方案2】:

    您可以按如下方式使用比较器链接

    int[][] points;
    // sorting the rows of a 2d array first by the
    // first column and then by the second column
    Arrays.sort(points, Comparator
            .<int[], Integer>comparing(arr -> arr[0])
            .thenComparing(arr -> arr[1]));
    

    另见:Sorting a 2d array in Java

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 1970-01-01
      • 2016-11-03
      • 2023-03-05
      • 2013-08-29
      • 2013-06-29
      • 2014-01-18
      • 2010-09-22
      相关资源
      最近更新 更多