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.
If there are multiple answers, you can return any of them.
Example
Example 1:
Input:
[
[1, 5, 7],
[3, 7, -8],
[4, -8 ,9]
]
Output: [[1, 1], [2, 2]]
Example 2:
Input:
[
[0, 1],
[1, 0]
]
Output: [[0, 0], [0, 0]]
Challenge
O(n3) time.
思路:用prefixsum,代表是从(0,0) 到(i,j) 的区域sum。然后固定上边界和下边界,然后扫描j,用hashmap来找有没有重复的区域,如果有就找到了区域为0的,然后记录答案,注意,因为prefixsum是+1了的index,所以,最后右下角的点需要减去1,左上角的点因为默认+1,所以不用减去1了。 O(N^3); Space O(N^2);
public class Solution {
/*
* @param matrix: an integer matrix
* @return: the coordinate of the left-up and right-down number
*/
public int[][] submatrixSum(int[][] matrix) {
int[][] res = new int[2][2];
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return res;
}
int m = matrix.length;
int n = matrix[0].length;
int[][] prefixSum = new int[m + 1][n + 1];
for(int i = 0; i <= m; i++) {
for(int j = 0; j <= n; j++) {
if(i == 0 || j == 0) {
prefixSum[i][j] = 0;
} else {
prefixSum[i][j] = prefixSum[i - 1][j] + prefixSum[i][j - 1] - prefixSum[i - 1][j - 1] + matrix[i - 1][j - 1];
}
}
}
for(int x1 = 0; x1 < m; x1++) {
for(int x2 = x1 + 1; x2 <= m; x2++) {
// 记住,这里每次循环都要新建一个hashmap;
HashMap<Integer, Integer> hashmap = new HashMap<>();
for(int j = 0; j <= n; j++) {
int area = prefixSum[x2][j] - prefixSum[x1][j];
if(hashmap.containsKey(area)) {
int k = hashmap.get(area);
res[0][0] = x1;
res[0][1] = k;
res[1][0] = x2 - 1;
res[1][1] = j - 1;
} else {
hashmap.put(area, j);
}
}
}
}
return res;
}
}