题目描述:
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.
Given matrix
[
[1 ,5 ,7],
[3 ,7 ,-8],
[4 ,-8 ,9],
]
return [(1,1), (2,2)]
O(n3) time.
这题用O(n^4)的代价解还是很直观的。先算出一个presum matrix,对于在presum中的每个元素(i, j),它的值为所有在matrix中<= i and <= j的值的和。然后用四层循环找到和为0的submatrix坐标。
但是题目的要求是O(n^3),这就要少一个循环了。那么这就意味着在找submatrix的坐标的时候,不确定元素从4个得变为3个。我认为一般少time complexity的代价就是增加space,那么怎么增加space来达到目的呢?这里看到当submatrix和为0时,有这样的等式关系:m[i][j] - m[i1][j] - m[i][j1] + m[i1][j1] = 0。把它重写一下,得到:m[i][j] - m[i1][j] = m[i][j1] - m[i1][j1]。可以看到等式每一边的变量都只有3个了。这里就可以想到,在遍历j时,可以用一个map把m[i][j] - m[i1][j]的值存起来。当找到另一个j1满足m[i][j1] - m[i1][j1]已经在map中存在时,就是我们要求的答案。
Mycode(AC = 113ms):
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) {
// Write your code here
vector<vector<int>> ans(2, vector<int>(2, 0));
// get size of the matrix
int num_rows = matrix.size();
if (num_rows == 0) {
return ans;
}
int num_cols = matrix[0].size();
// for each position (i, j), get the sum of all elements with position
// range (x <= i and y <= j)
vector<vector<int>> presum(num_rows + 1, vector<int>(num_cols + 1, 0));
for (int i = 1; i <= num_rows; i++) {
for (int j = 1; j <= num_cols; j++) {
int left_upper = presum[i - 1][j - 1];
int left = presum[i][j - 1];
int upper = presum[i - 1][j];
presum[i][j] = -left_upper + left + upper + matrix[i - 1][j - 1];
}
}
// take advantage that when submatrix == 0, the equation
// m[i][j] - m[i1][j] - m[i][j1] + m[i1][j1] = 0
// -> m[i][j] - m[i1][j] = m[i][j1] - m[i1][j1]
// in that case, only i, i1, j needs to be traversed
for (int i = 0; i < num_rows; i++) {
for (int i1 = i + 1; i1 <= num_rows; i1++) {
map<int, int> helper;
for (int j = 0; j <= num_cols; j++) {
int diff = presum[i1][j] - presum[i][j];
if (helper.find(diff) != helper.end()) {
ans[0][0] = i;
ans[0][1] = helper[diff];
ans[1][0] = i1 - 1;
ans[1][1] = j - 1;
return ans;
}
else {
helper[diff] = j;
}
}
}
}
return ans;
}
};