本文介绍了如何交换二维数组的行和列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一种方法,用于转置"二维整数数组,在其中交换原始矩阵的行和列.

I'm trying to write a method for 'transpose' a two-dimensional array of integers, in which the rows and columns of the original matrix are exchanged.

但是,我不知道该如何实现.如何写出这种方法?

However, I have no idea how I can realize this.How do I write out this method?

public class Matrix {
    private int[][] numbers;

    public Matrix(int rows, int colums) {
        if (rows < 1)
            rows = 1;
        else
            rows = rows;
        if (colums < 1)
            colums = 1;
        else
            colums = colums;
        numbers = new int[rows][colums];
    }

    public final void setNumbers(int[][] numbers) {
        this.numbers = numbers;
    }

    public int[][] getNumbers() {
        return numbers;
    }

    public int[][] transpose() {
        int[][] transpose = getNumbers();
        return numbers;
    }
}

推荐答案

您可以遍历行和列,并将每个元素[i,j]分配给转置的[j,i]:

You could iterate over the rows and columns and assign each element [i,j] to the transposed [j,i]:

/**
 * Transposses a matrix.
 * Assumption: mat is a non-empty matrix. i.e.:
 * 1. mat != null
 * 2. mat.length > 0
 * 3. For every i, mat[i].length are equal and mat[i].length > 0
 */
public static int[][] transpose(int[][] mat) {
    int[][] result = new int[mat[0].length][mat.length];
    for (int i = 0; i < mat.length; ++i) {
        for (int j = 0; j < mat[0].length; ++j) {
            result[j][i] = mat[i][j];
        }
    }
    return result;
}

这篇关于如何交换二维数组的行和列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 19:22