Sum of diagonal elements in a matrix

后端 未结 11 1950
轻奢々
轻奢々 2021-02-12 11:42

I am trying to find out the sum of the diagonal elements in a matrix. Here, n is the size of the square matrix and a is the matrix. Can someone explain this to me what is happen

11条回答
  •  借酒劲吻你
    2021-02-12 12:18

    O(n) time solution to find the diagonal difference of given multidimensional array.

    def diagonalDifference(arr):
            # arr[0][0], arr[1][1], arr[2][2]
            # arr[0][2], arr[1][1], arr[2][0]
            sumOfDiagonalFromLeft = 0
            sumOfDiagonalFromRight = 0
            pointIndexFromLeft = 0
            pointIndexFromLast = len(arr)-1
            for i in range(len(arr)):
                sumOfDiagonalFromLeft += arr[i][pointIndexFromLeft]
                # print(arr[i][pointIndexFromLeft])
                pointIndexFromLeft += 1
            
            for i in range(len(arr)):
                sumOfDiagonalFromRight += arr[i][pointIndexFromLast]
                # print(arr[i][pointIndexFromLast])
                if pointIndexFromLast < 0:
                    break
                else:
                    pointIndexFromLast -= 1
        
            diagonalDifference = abs(sumOfDiagonalFromLeft - sumOfDiagonalFromRight)
            return diagonalDifference
        
    arr = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]
    print(diagonalDifference(arr))
    

提交回复
热议问题