给定一个整数矩阵,请找出一个子矩阵,使得其数字之和等于0.输出答案时,请返回左上数字和右下数字的坐标。您在真实的面试中是否遇到过这个题?
Yes
样例
给定矩阵
[
[1 ,5 ,7],
[3 ,7 ,-8],
[4 ,-8 ,9],
]
返回 [(1,1), (2,2)]
挑战
O(n3) 时间复杂度。
标签 Expand
相关题目 Expand
解题思路:
当矩阵只有1列时,就是1*N在一维数组中,取出和为0的子串,就和子数组之和一样的。
http://blog.csdn.net/cumt_cx/article/details/48315551
比如:
1
3
-4
hashmap = {0=-1},sum = 0;
遍历一维数组sum +=arr[i],若hashmap中出现过则表示在这2次出现过程中的数之和为0;
当矩阵只有2列时候,用一个sum[ ]数组表示某一行的值,求出sum[ ]值,将sum[ ]
比如以下:
1 5 7
3 7 -8
4 -8 9
当求从1开始的2列矩阵中是否存在和为0的矩阵。
sum[ 3 ] = {1+5,3+7,4+-8};再以sum[ 3 ]作为一个新的一列数组,求子数组和。
同理N*M
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[][] res = new int[2][2];
if(null==matrix||0==matrix.length){
return res;
}
int m = matrix.length;
int n = matrix[0].length;
for(int i=0;i<n;i++){
int sum[] = new int[m];
for(int j=i;j<n;j++){
for(int k=0;k<m;k++){
sum[k] += matrix[k][j];
}
int lastsum = 0;
HashMap<Integer,Integer> map = new HashMap<>();
map.put(0, -1);
for(int v=0;v<m;v++){
lastsum +=sum[v];
if(map.containsKey(lastsum)){
res[0][0] = map.get(lastsum)+1;
res[0][1] = i;
res[1][0] = v;
res[1][1] = j;
return res;
}
map.put(lastsum, v);
}
}
}
return res;
}
}