HackerRank Java7求解对角线差遇运行时错误,请求代码排查
Hey there! I see you're just starting out on HackerRank and ran into a runtime error with your Diagonal Difference solution—let's get this sorted out quickly.
The Root Cause of the Runtime Error
Your code's issue comes down to an array index out of bounds in this line:
sum2 += a[n-i][i];
When i = 0, n - i equals n, but array indices start at 0. Since your matrix is n x n, the largest valid row index is n-1. Accessing a[n][0] tries to reach a row that doesn't exist, which triggers the runtime error.
The Correct Approach for the Reverse Diagonal
The reverse diagonal (from top-right to bottom-left) uses indices where the row index decreases as the column index increases. For each i (starting at 0), the correct row index is n-1 - i.
Fixed Code
Here's the corrected version of your function:
static int diagonalDifference(int[][] a) { int sum1 = 0; int sum2 = 0; int n = a[0].length; for(int i = 0; i < n; i++){ sum1 += a[i][i]; // Fixed the row index for the reverse diagonal sum2 += a[n-1 - i][i]; } return Math.abs(sum1 - sum2); }
Quick Check
Just to confirm: for an n x n matrix, this will correctly sum:
sum1: elements at (0,0), (1,1), ..., (n-1,n-1) (main diagonal)sum2: elements at (n-1,0), (n-2,1), ..., (0,n-1) (reverse diagonal)
This should resolve the runtime error and pass all HackerRank test cases.
内容的提问来源于stack exchange,提问作者f.c

