跳转题目
本题暴力可以做,猜到用差分,但是不熟,不知道二维差分怎么用,碰到用差分的题目太少了。
暴力算法:
class Solution {
public:vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {vector<vector<int>> ans(n,vector<int>(n,0));for(vector<int> it:queries){for(int i=it[0];i<=it[2];i++){for(int j=it[1];j<=it[3];j++){ans[i][j]++;}}}return ans;}
};
二维差分:
class Solution {
public:vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {vector<vector<int>> ans(n,vector<int>(n,0));vector<vector<int>> diff(n+1,vector<int>(n+1,0));for(vector<int> it:queries){diff[it[0]][it[1]]++;diff[it[2]+1][it[3]+1]++;diff[it[0]][it[3]+1]--;diff[it[2]+1][it[1]]--;}for(int i=0;i<n;i++)for(int j=1;j<n;j++) diff[i][j]+=diff[i][j-1];for(int i=1;i<n;i++)for(int j=0;j<n;j++) diff[i][j]+=diff[i-1][j];for(int i=0;i<n;i++)for(int j=0;j<n;j++) ans[i][j]=diff[i][j];return ans;}
};
思路参考:https://leetcode.cn/problems/increment-submatrices-by-one/solutions/2684930/er-wei-chai-fen-qiu-qian-zhui-he-shi-hen-i8g5/
多耗费10mb的空间,速度提高了10倍。