如何比较各个行的总和?

时间:2019-02-15 06:27:20

标签: java arrays rows columnsorting

我设法编写了将一行中的数字相加的代码,但是现在我不得不比较不同行的总和。什么样的代码比较数组行的总和?

我考虑过尝试一个if语句,但是一旦我知道了它,我就不确定如何获取不同的行然后进行比较,因为您不能真正做到sum> sum

public class MatrixLab {

    public int largestRowSum(int[][] matrix) {
        //Comment outline before coding!  
        int[][] nums = matrix;
        int sum = 0;
        int arraySum = 0;
        //add individual rows
        for(int r = 0; r < matrix.length; r++) {
           for(int c = 0; c < matrix[r].length; c++) {
              sum += nums[r][c];
           }
        }
        System.out.println( sum );
        //compare rows 

        //return the value
        System.out.println( arraySum );
    }

比较行后,需要返回值总和最大的行的索引。

2 个答案:

答案 0 :(得分:1)

请保留一个变量,该变量指示到目前为止的总和,以及是否还需要存储索引

 public int largestRowSum(int[][] matrix) {
    //Comment outline before coding!  
    int[][] nums = matrix;
    int sum = 0;
    int arraySum = 0;
    int maxSum = 0; // Indicates the max sum of row encountered till now
    int indexOfmaxSumRow = 0; // index of row which corresponds to maxsum
    //add individual rows
    for (int r = 0; r < matrix.length; r++) {
        for (int c = 0; c < matrix[r].length; c++) {
            sum += nums[r][c];
        }
        if (sum > maxSum) {
            maxSum = sum;
            indexOfmaxSumRow = r;
        }
    }
    System.out.println(sum);
    //compare rows 

    //return the value
    System.out.println(arraySum);
    return indexOfmaxSumRow;
}

答案 1 :(得分:0)

class Matrix
{
    public static void main(String arg[])
    {
        int[][] num = {{1,4,7},{12,5,56},{2,5,8},{3,6,9}};
        int index = new Matrix().Sum(num);
        System.out.println(""+index+" is index of the row with greatest sum.");
    }

    public int Sum(int[][] mat)
    {
        int val = 0,index=0;
        for(int i = 0;i<mat.length;i++)
        {
            int sum = 0;
            for(int j = 0; j<mat[i].length;j++)
            sum += mat[i][j];
            val = (i == 0 ? sum : val);
            if(val < sum)
            {
                val = sum;
                index = i;
            }
         }
         return index;
     }
}

希望可以帮助