描述:
给定一个整数矩阵,请找出一个子矩阵,使得其数字之和等于0.输出答案时,请返回左上数字和右下数字的坐标。
样例:
给定矩阵
[
[1 ,5 ,7],
[3 ,7 ,-8],
[4 ,-8 ,9],
]
返回 [(1,1), (2,2)]
思路:
求和:
1 6 13
4 16 15
8 12 20
求差:
k=0 | k=1 | k=2 | k=3 | |
i=0,j=1 | 0 | 1 | 6 | 13 |
i=0,j=2 | 0 | 4 | 16 | 15 |
i=0,j=3 | 0 | 8 | 12 | 20 |
i=1,j=2 | 0 | 3 | 10 | 2 |
i=1,j=3 | 0 | 7 | 6 | 7 |
i=2,j=3 | 0 | 4 | -4 | 5 |
public class Solution {
/**
* @param matrix an integer matrix
* @return the coordinate of the left-up and right-down number
*/
public int[][] submatrixSum(int[][] matrix) {
// Write your code here
int[][] result = new int[2][2];
if(matrix == null){
return result;
}
int row = matrix.length;
int column = matrix[0].length;
int[][] sum = new int[row+1][column+1];
for(int i = 0;i<=row;i++){
sum[i][0] = 0;
}
for(int j = 1;j<=column;j++){
sum[0][j] = 0;
}
for(int i = 0;i<row;i++){
for(int j = 0;j<column;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 j = i+1;j<=row;++j){
HashMap<Integer,Integer> record = new HashMap<Integer,Integer>();
for(int k = 0;k<=column;++k){
int temp = sum[j][k] - sum[i][k];
if(record.containsKey(temp)){
result[0][0] = i;
result[0][1] = record.get(temp);
result[1][0] = j-1;
result[1][1] = k-1;
return result;
}else{
record.put(temp , k);
}
}
}
}
return result;
}
}