繁体   English   中英

更改二维数组的列,就好像它是一维数组java

[英]Change Columns of 2D Array as if it Were a 1D Array java

我想知道是否有一种方法可以更改方法中的2D数组的列,而无需考虑整个数组并对其进行修改?

public static void main(String[] args){
  int[][] a = {{1,2,3},{4,5,6},{7,8,9}};
  int[] b = reverse(new int[]{1,2,3});
  System.out.println(Arrays.toString(b));
  System.out.println(Arrays.deepToString(a));
  System.out.println(Arrays.toString(new int[]{a[0][0],a[1][0],a[2][0]}));
  System.out.println(Arrays.deepToString(a));
}
public static int[] reverse(int[] start)
{
    int[] result = new int[start.length];
    int x = 0;
    for(int i= start.length-1; i >= 0; i --)
    {
        result[i] = start[x];
        x ++;
    }
    return result;
}

当前,它将反转输入的数字,但不会修改a[0][0]a[1][0]a[2][0] 原始数组保持不变,但是修改了创建的新数组。 我该如何解决?

您可以先对内部子数组进行排序,然后对外部父数组进行排序,以实现此目的。

    //Array for testing
    int[][] a = {{1,2,3},{4,5,6},{7,8,9}};
    System.out.println(Arrays.deepToString(a));

    //loop through inner array only and reverse items
    for (int i = 0; i < a.length; i++){
        a[i] = reverse(a[i]);
    }
    System.out.println(Arrays.deepToString(a));

    //loop through outer array only and reverse parents.
    //Note that this only needs to goe through half the array that is why we use "a.length / 2".
    for (int i = 0; i < a.length / 2; i++){
        int[] temp = a[i];
        a[i] = a[a.length - i - 1];
        a[a.length - i - 1] = temp;
    }
    System.out.println(Arrays.deepToString(a));

输出:

    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    [[3, 2, 1], [6, 5, 4], [9, 8, 7]]
    [[9, 8, 7], [6, 5, 4], [3, 2, 1]]

暂无
暂无

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

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