二維字首和&差分

fufuaifufu發表於2024-11-22
  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;
    }
};

相關文章