2023. 1. 27. 14:47ㆍJava/coding test
Diagonal Difference
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
1 2 3 4 5 6 9 8 9
The left-to-right diagonal . The right to left diagonal . Their absolute difference is .
Function description
Complete the function in the editor below.
diagonalDifference takes the following parameter:
- int arr[n][m]: an array of integers
Return
- int: the absolute diagonal difference
Input Format
The first line contains a single integer, , the number of rows and columns in the square matrix .
Each of the next lines describes a row, , and consists of space-separated integers .
Constraints
Output Format
Return the absolute difference between the sums of the matrix's two diagonals as a single integer.
Sample Input
3 11 2 4 4 5 6 10 8 -12
Sample Output
15
Explanation
The primary diagonal is:
11 5 -12
Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:
4 5 10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15
Note: |x| is the absolute value of x
row와 col이 같은 행렬이 입력으로 주어질 때, 각 대각선의 합의 차를 구하는 코드를 작성하면 됩니다.
2중배열에서 배열 하나씩 읽으면서, cnt에 따라 앞에서 읽은 것은 primary에 합산하고 뒤에서 읽은 것은 secondary에 합산하면 됩니다.
static int diagonalDifference(List<List<Integer>> arr) { int primary = 0, secondary = 0; int cnt = 0, length = arr.size(); for (List<Integer> a : arr) { primary += a.get(cnt); secondary += a.get(length - cnt - 1); cnt++; } return Math.abs(primary - secondary); }
'Java > coding test' 카테고리의 다른 글
[HackerRank - Java] Day 3 - 2. Tower Breakers (0) | 2023.01.28 |
---|---|
[HackerRank - Java] Day 2 - 3. Counting Sort 1 (0) | 2023.01.27 |
[HackerRank - Java] Day 2 - 1. Lonely Integer (0) | 2023.01.27 |
[HackerRank - Java] Day 1 - 3. Time Conversion (0) | 2023.01.27 |
[HackerRank - Java] Day 1 - 2. Mini-Max Sum (0) | 2023.01.27 |