304.range-sum-query-2d-immutable.go 852 B

123456789101112131415161718192021222324252627282930
  1. type NumMatrix struct {
  2. acc [][]int
  3. }
  4. func Constructor(matrix [][]int) (numMat NumMatrix) { // Constructor O(n^2), SumRegion O(1)
  5. rows := len(matrix)
  6. if rows == 0 {
  7. return
  8. }
  9. cols := len(matrix[0])
  10. numMat.acc = make([][]int, rows+1)
  11. for i := 0; i <= rows; i++ {
  12. numMat.acc[i] = make([]int, cols+1)
  13. for sum, j := 0, 1; i != 0 && j <= cols; j++ {
  14. sum += matrix[i-1][j-1] // sum is the sum of curr row
  15. numMat.acc[i][j] = sum + numMat.acc[i-1][j] // accumulate curr col
  16. }
  17. }
  18. return
  19. }
  20. func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) (sum int) {
  21. return this.acc[row2+1][col2+1] - this.acc[row2+1][col1] - this.acc[row1][col2+1] + this.acc[row1][col1]
  22. }
  23. /**
  24. * Your NumMatrix object will be instantiated and called as such:
  25. * obj := Constructor(matrix);
  26. * param_1 := obj.SumRegion(row1,col1,row2,col2);
  27. */