Subarray/Submatrix Target Sum

Leetcode 560. Subarray Sum Equals K

求一个数组中和等于k的子数组的个数

分析:prefix sum + map,当前的prefix sum为cur,之前出现过的prefix sum存到counter中(因为存在负数,可能有多个prefix sum相等,因此counter[x]表示prefix sum == x的个数),

则以当前点为endpoint的子数组和等于K的个数为counter[cur - k]

time O(n) 

space O(n)

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        int res = 0, cur = 0;
        unordered_map<int, int> counter;
        counter[0] = 1;
        for(int i = 0; i < nums.size(); ++i){
            cur += nums[i];
            res += counter[cur - k];
            counter[cur]++;
        }
        return res;
    }
};

 Leetcode 1074. Number of Submatrices That Sum to Target

求一个矩阵中和等于target的子矩阵的个数

分析:矩阵每一行,计算prefix sum,然后对于任意两列,计算行的累加和,问题就转换为了Subarray Sum Equals K

time O($n^3$)

space O(n)

class Solution {
public:
    int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
        int m = matrix.size(), n = matrix[0].size();
        for(int i = 0; i < m; ++i){
            for(int j = 1; j < n; ++j){
                matrix[i][j] += matrix[i][j - 1];
            }
        }
        int res = 0;
        for(int i = 0; i < n; ++i){
            for(int j = i; j < n; ++j){
                //计算列i与列j之间且宽为j-i+1的所有和等于target的子矩阵个数
                //等价与将问题转换为了Subarray Sum Equals K
                unordered_map<int, int> counter;
                counter[0] = 1;
                int cur = 0;
                for(int k = 0; k < m; ++k){
                    cur += matrix[k][j] - (i > 0 ? matrix[k][i - 1] : 0);
                    res += counter[cur - target];
                    counter[cur]++;
                }
            }
        }
        return res;
    }
};

 

posted @ 2019-10-09 15:59  betaa  阅读(169)  评论(0编辑  收藏  举报