[LintCode] Submatrix Sum 子矩阵之和

时间:2023-03-09 01:43:32
[LintCode] Submatrix Sum 子矩阵之和

Given an integer matrix, find a submatrix where the sum of numbers is zero. Your code should return the coordinate of the left-up and right-down number.

Have you met this question in a real interview?
Yes
Example

Given matrix

[
[1 ,5 ,7],
[3 ,7 ,-8],
[4 ,-8 ,9],
]

return [(1,1), (2,2)]

Challenge

O(n3) time.

这道题跟LeetCode上的那道Max Sum of Rectangle No Larger Than K很类似。

解法一:

class Solution {
public:
/**
* @param matrix an integer matrix
* @return the coordinate of the left-up and right-down number
*/
vector<vector<int>> submatrixSum(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[].empty()) return {};
vector<vector<int>> sums = matrix;
int m = matrix.size(), n = matrix[].size();
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
int t = sums[i][j];
if (i > ) t += sums[i - ][j];
if (j > ) t += sums[i][j - ];
if (i > && j > ) t -= sums[i - ][j - ];
sums[i][j] = t;
for (int p = ; p <= i; ++p) {
for (int q = ; q <= j; ++q) {
int d = sums[i][j];
if (p > ) d -= sums[p - ][j];
if (q > ) d -= sums[i][q - ];
if (p > && q > ) d += sums[p - ][q - ];
if (d == ) return {{p, q}, {i, j}};
}
}
}
}
printVec(sums);
return {};
}
};

解法二:

class Solution {
public:
/**
* @param matrix an integer matrix
* @return the coordinate of the left-up and right-down number
*/
vector<vector<int>> submatrixSum(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[].empty()) return {};
int m = matrix.size(), n = matrix[].size();
for (int i = ; i < n; ++i) {
vector<int> sums(m, );
for (int j = i; j < n; ++j) {
for (int k = ; k < m; ++k) {
sums[k] += matrix[k][j];
}
int curSum = ;
unordered_map<int, int> map{{,-}};
for (int k = ; k < m; ++k) {
curSum += sums[k];
if (map.count(curSum)) return {{map[curSum] + , i}, {k, j}};
map[curSum] = k;
}
}
}
return {};
}
};

参考资料:

http://www.jiuzhang.com/solutions/submatrix-sum/