forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 0304-range-sum-query-2d-immutable.kt
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
class NumMatrix(matrix: Array<IntArray>) { | ||
|
||
val row = matrix.size | ||
val col = matrix[0].size | ||
val prefixSum = Array(row + 1){ IntArray(col + 1) } | ||
|
||
init { | ||
for(i in 0 until row) { | ||
var prefix = 0 | ||
for(j in 0 until col) { | ||
println("i: $i j: $j") | ||
prefix += matrix[i][j] | ||
prefixSum[i + 1][j + 1] = prefix + prefixSum[i][j + 1] | ||
} | ||
} | ||
} | ||
|
||
|
||
fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int { | ||
val r1 = row1 + 1 | ||
val r2 = row2 + 1 | ||
val c1 = col1 + 1 | ||
val c2 = col2 + 1 | ||
|
||
val botRight = prefixSum[r2][c2] | ||
val aboveOf = prefixSum[r1 - 1][c2] | ||
val leftOf = prefixSum[r2][c1 - 1] | ||
val topLeft = prefixSum[r1 - 1][c1 - 1] | ||
|
||
return botRight - aboveOf - leftOf + topLeft | ||
} | ||
|
||
} | ||
|
||
/** | ||
* Your NumMatrix object will be instantiated and called as such: | ||
* var obj = NumMatrix(matrix) | ||
* var param_1 = obj.sumRegion(row1,col1,row2,col2) | ||
*/ |