给定一个整数矩阵,请找出一个子矩阵,使得其数字之和等于0.输出答案时,请返回左上数字和右下数字的坐标。
样例:
给定矩阵
[
[1 ,5 ,7],
[3 ,7 ,-8],
[4 ,-8 ,9],
]
返回 [(1,1), (2,2)]
挑战 :
O(
n3
) 时间复杂度。
#ifndef C405_H
#define C405_H
#include<iostream>
#include<vector>
#include<map>
using namespace std;
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>> res;
if (matrix.empty())
return res;
res = vector<vector<int>>(2, vector<int>(2, 0));
int row = matrix.size();
int col = matrix[0].size();
vector<vector<int>> sum(row + 1, vector<int>(col + 1, 0));
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
sum[i + 1][j + 1] = matrix[i][j] + sum[i][j + 1] + sum[i + 1][j] - sum[i][j];
}
}
for (int i = 0; i < row; ++i)
{
for (int i1 = i + 1; i1 <= row; ++i1)
{
map<int, int> m;
for (int j = 0; j <= col; ++j)
{
int diff = sum[i1][j] - sum[i][j];
if (m.find(diff) != m.end())
{
res[0] = { i, m[diff] };
res[1] = { i1 - 1, j - 1 };
return res;
}
else
m[diff] = j;
}
}
}
return res;
}
};
#endif