Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
range-sum-query-2d-immutable.cpp 1.08 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2015-11-25 18:39 +08:00 . Update range-sum-query-2d-immutable.cpp
// Time: ctor: O(m * n),
// lookup: O(1)
// Space: O(m * n)
class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) {
if (matrix.empty()) {
return;
}
const auto m = matrix.size(), n = matrix[0].size();
for (int i = 0; i <= m; ++i) {
sums_.emplace_back(n + 1, 0);
}
for (int i = 1; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
sums_[i][j] = sums_[i][j - 1] + matrix[i - 1][j - 1];
}
}
for (int j = 0; j <= n; ++j) {
for (int i = 1; i <= m; ++i) {
sums_[i][j] += sums_[i - 1][j];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sums_[row2 + 1][col2 + 1] - sums_[row2 + 1][col1] -
sums_[row1][col2 + 1] + sums_[row1][col1];
}
private:
vector<vector<int>> sums_;
};
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助