[算法] 剑指offer2 golang 面试题13:二维子矩阵的数字之和

[算法] 剑指offer2 golang 面试题13:二维子矩阵的数字之和

题目1:

在这里插入图片描述

思路1: 暴力模拟

暴力模拟

代码

type NumMatrix struct {
    Matrix [][]int
}
func Constructor(matrix [][]int) NumMatrix {
    return NumMatrix{Matrix: matrix}
}
//start: 17:05
//二维子矩阵的元素和
//思路: 遍历子矩阵的每一行累加值即可
func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
    //参数处理 todo

    //矩阵
    //行i,列j
    sum := 0
    for i:=row1; i <= row2; i++ {
         for j:=col1; j <= col2; j++{
             sum += this.Matrix[i][j]
         } 
    }
    return sum
}


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

在这里插入图片描述

思路2: 提前算好每个区域的值然后最后计算

比如计算蓝色区域1的值可以等于红色区域2减去绿色区域3和其他区域4和5

我们在构造的时候记录好矩形左上到右下位置的值然后获得每个区域的时候时间复杂度是 O(1)

在这里插入图片描述

代码2

type NumMatrix struct {
    sums [][]int
}


func Constructor(matrix [][]int) NumMatrix {
    //第一行
    for j:=1; j < len(matrix[0]); j++{
        matrix[0][j] = matrix[0][j-1] + matrix[0][j]
    }
    
    //第2-n行
    for i:=1; i < len(matrix); i++ {
        sum := 0
         for j:=0; j < len(matrix[0]); j++{
             sum += matrix[i][j]
             matrix[i][j] = sum + matrix[i-1][j]
         } 
    }

    return NumMatrix{sums: matrix}
}

//start: 17:05
//二维子矩阵的元素和
//思路2: 提前计算好(0,0)到每个点的sum然后第二次计算就能O(1)
//a1 - a2 - a3 -a4
func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
    a1 := this.sums[row2][col2]
    a2 := 0
    a3 := 0
    a4 := 0

    if row1 >= 1 {
        a2 = this.sums[row1-1][col1]
        if col1 >= 1 {
            a2 = this.sums[row1-1][col1-1]
        }
    }
    if row1 >= 1 {
        a3 = this.sums[row1-1][col2] - a2
    }
    if col1 >= 1 {
        a4 = this.sums[row2][col1-1] - a2
    }

    return a1 - a2 - a3 - a4
}


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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JarvanStack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值