繁体   English   中英

Java 如何打印已排序的二维数组的原始索引?

[英]Java How to print the original index of a sorted 2d array?

假设我有一个 5X1 二维数组 [2,3,1,4,5],所以索引将是 [[0,0],[1,0],[2,0],[3,0],[ 4,0]] 仍然存在,但是如何让原始索引保持在值中? 这样我就可以在对值进行排序后打印出索引(如果有意义的话),例如

排序后的值将是 [1,2,3,4,5],但索引将是 [2,0][0,0][1,0][3,0][4,0] 究竟如何你操纵它吗? 提前致谢,将不胜感激!

{
 int[][] array = new int[5][1];

 array = {{2,3,1,4,5}};
 //at this point the array index will be [[0,0],[1,0],[2,0],[3,0],[4,0]]

 Arrays.sort(array);
 //i want the index to stay within the value after sorting...

} 

奇怪的问题。 我会完全重构代码以使用我自己的自定义对象,该对象不仅包含值,还包含原始位置。

另一种方法是编写您自己的排序,但是在排序时,保留具有原始位置的第二个数组,并且您对第一个数组所做的所有操作都会镜像到第二个数组。

第三种方法:如果保证数组的值是唯一的,您可以先复制数组。 调用一个 origArray 和一个 sortedArray。 然后,当查看 sortedArray 中的一个项目时,在 origArray 中找到它,它会告诉你它曾经在哪里。 但这取决于值的唯一性,这是一个糟糕的假设。

您可能想重新编辑您的问题。 您的数组分配的语法不正确。

应该如下所示。

  v = new int[][]{{2},{3},{1},{4},{5}};

一旦你改变了它,你就不能那样使用 sort 了。

为了解决您的问题,我将创建一个映射,将索引映射到其原始值。 如前所述,我还更改了数组分配。

      int[][] vals;
      vals = new int[][] { { 12, 31, 21, 75, 15
            }
      };

      Map<Integer, Integer> indices =
            IntStream.range(0, vals[0].length).boxed().collect(
                  Collectors.toMap(i -> i, i -> vals[0][i]));

      indices.forEach((k, v) -> System.out.println(k + " => " + v));

      Arrays.sort(vals[0]);

      System.out.println(Arrays.toString(vals[0]));

这打印

0 => 12
1 => 31
2 => 21
3 => 75
4 => 15
[12, 15, 21, 31, 75]

如果要将值映射到原始索引,只需将参数反向到Collector

    Collectors.toMap(i -> vals[0][i], i->i)

假设我有一个5X1 2D数组[2,3,1,4,5],所以索引将是[[0,0],[1,0],[2,0],[3,0],[ 4,0]]仍然存在,但是如何使原始索引保留在值中? 因此,我可以在对值进行排序后打印出索引(如果有意义的话),例如

排序后的值将是[1,2,3,4,5],但是索引将是[2,0] [0,0] [1,0] [3,0] [4,0]你操纵它吗? 在此先感谢您,我们将不胜感激!

{
 int[][] array = new int[5][1];

 array = {{2,3,1,4,5}};
 //at this point the array index will be [[0,0],[1,0],[2,0],[3,0],[4,0]]

 Arrays.sort(array);
 //i want the index to stay within the value after sorting...

} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM