halfrost / LeetCode-Go

✅ Solutions to LeetCode by Go, 100% test coverage, runtime beats 100% / LeetCode 题解
https://books.halfrost.com/leetcode
MIT License
32.76k stars 5.68k forks source link

在这个库学习,并附上1572 Matrix Diagonal Sum的golang题解 #134

Closed tphyhFighting closed 3 years ago

tphyhFighting commented 3 years ago
func diagonalSum(mat [][]int) int {
    n := len(mat)
    ans := 0
    for pi := 0; pi < n; pi++ {
        ans += mat[pi][pi]
    } 
    for si, sj := n - 1, 0; sj < n; si, sj = si - 1, sj + 1 {
        ans += mat[si][sj]
    }
    if n % 2 == 0 {
        return ans
    }
    return ans - mat[n / 2][n / 2]
}

2021-05-20 11-30-43 的屏幕截图.png

halfrost commented 3 years ago

感谢你的 PR,已经合并进去啦。