如何比较各个行的总和?

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


我想尝试一个 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 );

    }

它需要在比较行之后返回具有最大值总和的行的索引


ITMISS
浏览 114回答 2
2回答

慕标5832272

保留一个表示最大总和的变量,如果你也想要存储索引&nbsp;public int largestRowSum(int[][] matrix) {&nbsp; &nbsp; //Comment outline before coding!&nbsp;&nbsp;&nbsp; &nbsp; int[][] nums = matrix;&nbsp; &nbsp; int sum = 0;&nbsp; &nbsp; int arraySum = 0;&nbsp; &nbsp; int maxSum = 0; // Indicates the max sum of row encountered till now&nbsp; &nbsp; int indexOfmaxSumRow = 0; // index of row which corresponds to maxsum&nbsp; &nbsp; //add individual rows&nbsp; &nbsp; for (int r = 0; r < matrix.length; r++) {&nbsp; &nbsp; &nbsp; &nbsp; for (int c = 0; c < matrix[r].length; c++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sum += nums[r][c];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (sum > maxSum) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxSum = sum;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; indexOfmaxSumRow = r;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(sum);&nbsp; &nbsp; //compare rows&nbsp;&nbsp; &nbsp; //return the value&nbsp; &nbsp; System.out.println(arraySum);&nbsp; &nbsp; return indexOfmaxSumRow;}

温温酱

class Matrix{&nbsp; &nbsp; public static void main(String arg[])&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; int[][] num = {{1,4,7},{12,5,56},{2,5,8},{3,6,9}};&nbsp; &nbsp; &nbsp; &nbsp; int index = new Matrix().Sum(num);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(""+index+" is index of the row with greatest sum.");&nbsp; &nbsp; }&nbsp; &nbsp; public int Sum(int[][] mat)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; int val = 0,index=0;&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0;i<mat.length;i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int sum = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int j = 0; j<mat[i].length;j++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sum += mat[i][j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val = (i == 0 ? sum : val);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(val < sum)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val = sum;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; index = i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return index;&nbsp; &nbsp; &nbsp;}}希望这会有所帮助
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java