Leetcode - Range Sum Query - Immutable
Leetcode - Longest Continuous Increasing Subsequence

Leetcode - Range Sum Query 2D - Immutable

violet posted @ May 09, 2020 05:15:42 AM in 算法 with tags Algorithm Golang PrefixSum , 233 阅读

https://leetcode.com/problems/range-sum-query-2d-immutable/

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [
  [3, 0, 1, 4, 2],
  [5, 6, 3, 2, 1],
  [1, 2, 0, 1, 5],
  [4, 1, 0, 1, 7],
  [1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

 

type NumMatrix struct {
    sum [][]int
}


func Constructor(matrix [][]int) NumMatrix {
    if len(matrix) == 0 || len(matrix[0]) == 0 {
        return NumMatrix{}
    }
    m := len(matrix)
    n := len(matrix[0])
    sum := make([][]int, m)
    for i := 0; i < m; i++ {
        sum[i] = make([]int, n)
    }
    result := 0
    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            result += matrix[i][j]
            if i == 0 && j == 0 {
                sum[0][0] = matrix[0][0]
                continue
            }
            if i != 0 && j != 0 {
                sum[i][j] = sum[i-1][j] + sum[i][j-1] + matrix[i][j] - sum[i-1][j-1]
            }
            if i == 0 {
                sum[i][j] = sum[i][j-1] + matrix[i][j]
            } else if j == 0 {
                sum[i][j] = sum[i-1][j] + matrix[i][j]
            }
        }
    }
    
    return NumMatrix{
        sum: sum,
    }
}


func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
    if row1 == 0 && col1 == 0 {
        return this.sum[row2][col2]
    }
    
    if row1 == 0 && col1 != 0 {
        return this.sum[row2][col2] - this.sum[row2][col1-1]
    }
    if row1 != 0 && col1 == 0 {
        return this.sum[row2][col2] - this.sum[row1-1][col2]
    }
    
    return this.sum[row2][col2] - this.sum[row1-1][col2] - this.sum[row2][col1-1] + this.sum[row1-1][col1-1]
}


/**
 * Your NumMatrix object will be instantiated and called as such:
 * obj := Constructor(matrix);
 * param_1 := obj.SumRegion(row1,col1,row2,col2);
 */

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter