我正在对黑客进行挑战,想知道为什么我会遇到运行时错误,甚至是错误的答案。问题是:
给出一个正方形矩阵,计算其对角线之和之间的绝对差。
示例:
3 11 2 4 4 5 6 10 8 -12
输出:15
(第一行包含一个整数,即矩阵arr中的行数和列数)。
这是我的代码:
func diagonalDifference(arr: [[Int]]) -> Int {
let n = arr[0][0]
var diagonal1 = 0
var diagonal2 = 0
for index in 1...n {
diagonal1 += arr[index][index - 1]
diagonal2 += arr[index][n - index]
}
return abs(diagonal1 - diagonal2)
}
我似乎找不到为什么不起作用。
答案 0 :(得分:2)
对于输入的输入方式,我有相同的问题,但是我尝试了此解决方案,并且有效。
func diagonalDifference(arr: [[Int]]) -> Int {
var n = arr.count
var primaryDiagonalSum = 0
var secondaryDiagonalSum = 0
for index in 0..<n {
primaryDiagonalSum += arr[index][index]
secondaryDiagonalSum += arr[index][n-index-1]
}
let difference = abs(primaryDiagonalSum - secondaryDiagonalSum)
return difference
}
答案 1 :(得分:0)
var rsum = 0 //right diagonal sum
var lsum = 0 // left diagonal sum
var j = 0 // index to start from start for right diagonal sum
var k = arr.count-1 // index to start from end for left diagonal sum
for i in 0...k { //looping from first index to last index
rsum += arr[i][j] //right diagonal sum
lsum += arr[i][k] //left diagonal sum
j += 1
k -= 1
}
return abs(lsum - rsum)