LeetCode 304 Range Sum Query 2D - Immutable(范围求和2D - 不可变)

翻译

给定一个2D矩阵matrix,找出其中以左上角(row1,col1)和右下角(row2,col2)定义的矩形边界的元素的和。(译者注:包括边界)

这里写图片描述

以上矩形 范围内的元素和为8。

例如,
给定 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

备注:
你可以假定矩阵不会变化。
此处会有很多次对于sumRegion函数的调用。
你可以假定 row1 ≤ row2 以及 col1 ≤ col2 。

原文

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).

这里写图片描述

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
Note:
You may assume that the matrix does not change.
There are many calls to sumRegion function.
You may assume that row1 ≤ row2 and col1 ≤ col2.

分析

可以参考相关的上一道题,其实方法是类似的。

LeetCode 307 Range Sum Query - Mutable(范围和查询-可变)

原始方法

我们首先也还是用原始方法,但这次并不能通过了,原因大家都懂,太慢了。

class NumMatrix {
private:
    vector<vector<int>> matrixV;
public:
    NumMatrix(vector<vector<int>> &matrix) {
        matrixV = matrix;
    }

    int sumRegion(int row1, int col1, int row2, int col2) {
        int sum = 0;
        for (int i = row1; i <= row2; i++) {
            for (int j = col1; j <= col2; j++) {
                sum += matrixV[i][j];
            }
        }
        return sum;
    }
};

然后企图更具上一题的开方划分的方式来解决,努力了很长时间还是无果……

哎,还是要多学些算法,应该遇到问题就能知道哪些方法注定无果,不然一直尝试太累了………………再也不想通过for循环来解决问题了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值