본문 바로가기

알고리즘

해커랭크 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


내 코드 

func diagonalDifference(arr: [[Int]]) -> Int {
    // Write your code here
    var arrSize = arr.count
    var result:Int = 0
    var a:Int = 0
    var b:Int = 0

    for i in 0..<arrSize {
        a += arr[i][i]
        b += arr[i][arrSize-i-1]
    }
    result = abs(a - b)

    return result
}

 

이번 문제에서는 Swift의 절대값을 구하는 함수가 abs()라는 것을 알게되었다!!

알고리즘을 공부하니 소소하게 알게되는게 많은 것 같다! 

'알고리즘' 카테고리의 다른 글

[LeetCode] Two Sum  (0) 2021.08.31
해커랭크 Staircase  (0) 2020.09.11
해커랭크 Compare the Triplets 문제풀이  (0) 2020.09.04