如何在不使用存储阵列的情况下将二维阵列旋转 90 度?

2023-09-25Java开发问题
2

本文介绍了如何在不使用存储阵列的情况下将二维阵列旋转 90 度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我被指示不要使用存储阵列来完成此任务.基本上,我们必须创建一个将二维数组的内容旋转 90 度的函数.

I was instructed not to use a storage array to complete this task. Basically, we have to create a function that rotates the contents of a 2d array 90 degrees.

所以如果我从这个数组开始:

So if I start off with this array:

int[][] array = {{1,2,3}, {4,5,6}, {7,8,9}};

函数应该返回一个像这样的数组:

The function should return an array like this:

{{7,4,1}, {8,5,2}, {9,6,3}}

同样,我们不允许在函数中使用创建的数组进行存储.没有存储阵列是否也能做到这一点?

Again we are not allowed to use a created array within the function for storage. Is it even possible to accomplish this without a storage array?

推荐答案

您可以通过将上半部分与下半部分一一交换来旋转/转置数组:

You can rotate/transpose the array by swapping the upper half with the lower half one by one:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        int[][] array = new int[][] {
            new int[] { 1, 2, 3},
            new int[] { 4, 5, 6},
            new int[] { 7, 8, 9},
        };

        for (int row = 0; row < 3; row++) {
            for (int col = 0; col < row; col++) {
                int t = array[row][col];
                array[row][col] = array[col][row];
                array[col][row] = t;
            }
        }

        for (int row = 0; row < 3; row++) {
            System.out.println(Arrays.toString(array[row]));
        }
    }
}

这篇关于如何在不使用存储阵列的情况下将二维阵列旋转 90 度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13