这个算法如何使用 Array.sort(T[] a, Comparator<? super T> c) 对 n x 2 矩阵进行排序?

问题描述 投票:0回答:0
Arrays.sort(nx2Matrix, (a, b) -> {
    if (a[0] == b[0]) return a[1] - b[1];
    else return a[0] - b[0];
});

这将 n x 2 矩阵主要按第一个索引按升序排序,然后是第二个,因为它应该:

[[2, 0], [4, 1], [1, 2], [2, 3], [5, 4]]

变成

[[1, 2], [2, 0], [2, 3], [4, 1], [5, 4]]

但是它到底是怎么做到的呢?更具体地说,比较器在做什么? (这是来自 https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/editorial/ 的方法 1)

我试着阅读 Comparator 的文档,但它对我来说没有意义。我也尝试使用打印语句来查看到底发生了什么,但我仍然不明白它是如何对矩阵进行排序的。

java algorithm sorting matrix comparator
© www.soinside.com 2019 - 2024. All rights reserved.