2536.子矩阵元素加1
链接:2536.子矩阵元素加1
难度:Medium
标签:数组、矩阵、前缀和
简介:返回执行完所有操作后得到的矩阵 mat 。
题解 1 - cpp
- 编辑时间:2023-01-15
- 执行用时:316ms
- 内存消耗:86.8MB
- 编程语言:cpp
- 解法介绍:差分。
class Solution {
public:
vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {
vector<vector<int>> list(n + 1, vector<int>(n + 1, 0)), ans(n, vector<int>(n, 0));
for (auto &q : queries)
for (int i = q[0]; i <= q[2]; i++)
list[i][q[1]]++, list[i][q[3] + 1]--;
for (int i = 0; i < n; i++) {
int cur = 0;
for (int j = 0; j < n; j++)
cur += list[i][j], ans[i][j] = cur;
}
return ans;
}
};
题解 2 - rust
- 编辑时间:2023-01-15
- 执行用时:92ms
- 内存消耗:5.5MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
pub fn range_add_queries(n: i32, queries: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let n = n as usize;
let (mut list, mut ans) = (vec![vec![0; n + 1]; n + 1], vec![vec![0; n]; n]);
for q in queries {
let mut i = q[0];
while i <= q[2] {
list[i as usize][q[1] as usize] += 1;
list[i as usize][(q[3] + 1) as usize] -= 1;
i += 1;
}
}
for i in 0..n {
let mut cur = 0;
for j in 0..n {
cur += list[i][j];
ans[i][j] = cur;
}
}
ans
}
}