diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/README.md" index 32ca8a9344f3c..2113b8e0ab836 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/README.md" @@ -254,6 +254,36 @@ class NumMatrix { */ ``` +#### Swift + +```swift +class NumMatrix { + private var prefixSum: [[Int]] + + init(_ matrix: [[Int]]) { + let m = matrix.count + let n = matrix[0].count + prefixSum = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1) + + for i in 1...m { + for j in 1...n { + prefixSum[i][j] = prefixSum[i - 1][j] + prefixSum[i][j - 1] - prefixSum[i - 1][j - 1] + matrix[i - 1][j - 1] + } + } + } + + func sumRegion(_ row1: Int, _ col1: Int, _ row2: Int, _ col2: Int) -> Int { + return prefixSum[row2 + 1][col2 + 1] - prefixSum[row2 + 1][col1] - prefixSum[row1][col2 + 1] + prefixSum[row1][col1] + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * let obj = NumMatrix(matrix); + * let param_1 = obj.sumRegion(row1,col1,row2,col2); + */ +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.swift" new file mode 100644 index 0000000000000..e322fe13bc7a5 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/Solution.swift" @@ -0,0 +1,25 @@ +class NumMatrix { + private var prefixSum: [[Int]] + + init(_ matrix: [[Int]]) { + let m = matrix.count + let n = matrix[0].count + prefixSum = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1) + + for i in 1...m { + for j in 1...n { + prefixSum[i][j] = prefixSum[i - 1][j] + prefixSum[i][j - 1] - prefixSum[i - 1][j - 1] + matrix[i - 1][j - 1] + } + } + } + + func sumRegion(_ row1: Int, _ col1: Int, _ row2: Int, _ col2: Int) -> Int { + return prefixSum[row2 + 1][col2 + 1] - prefixSum[row2 + 1][col1] - prefixSum[row1][col2 + 1] + prefixSum[row1][col1] + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * let obj = NumMatrix(matrix); + * let param_1 = obj.sumRegion(row1,col1,row2,col2); + */ \ No newline at end of file