二维前缀和&差分

  1. 元素和小于等于 k 的子矩阵的数目
    题目链接:https://leetcode.cn/problems/count-submatrices-with-top-left-element-and-sum-less-than-k/description/
    题解代码:
class Solution {
public:
    int countSubmatrices(vector<vector<int>>& grid, int k) {
        int ans=0,m=grid.size(),n=grid[0].size();
        vector<vector<int>> sum(m+1,vector<int>(n+1));
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                sum[i+1][j+1]=sum[i+1][j]+sum[i][j+1]-sum[i][j]+grid[i][j];
                if(sum[i+1][j+1]<=k) ans+=1;
            }
        }
        return ans;
    }
};
  1. 子矩阵元素加 1
    题目链接:https://leetcode.cn/problems/increment-submatrices-by-one/description/
    题解代码:
class Solution {
public:
    vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {
        vector<vector<int>> diff(n + 1, vector<int>(n + 1)); 
        for (vector<int>& q: queries) {
            int row1 = q[0];
            int col1 = q[1];
            int row2 = q[2] + 1;
            int col2 = q[3] + 1;
            diff[row1][col1]++;
            diff[row1][col2]--;
            diff[row2][col1]--;
            diff[row2][col2]++;
        } 
        vector<vector<int>> res(n, vector<int>(n));
        res[0][0] = diff[0][0];  
        for (int j = 1; j < n; ++j) {  
            res[0][j] += res[0][j - 1] + diff[0][j];
        }
        for (int i = 1; i < n; ++i) {
            res[i][0] = res[i - 1][0] + diff[i][0];
            for (int j = 1; j < n; ++j) {
                res[i][j] = res[i - 1][j] + res[i][j - 1] - res[i - 1][j - 1] + diff[i][j];
            }
        }
        
        return res;
    }
};
posted @ 2024-11-22 01:16  fufuaifufu  阅读(9)  评论(0编辑  收藏  举报