[LintCode]Submatrix Sum



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.

Example

Given matrix

[
  [1 ,5 ,7],
  [3 ,7 ,-8],
  [4 ,-8 ,9],
]

return [(1,1), (2,2)]


这个题其实有点brain fuck。。锁定sum=0的submatrix是通过扫所有的左上角submatrix的差值去确定的。在i 上下界确定情况下,如果存在俩个submatrix sum一样,必然其差值部分的submatrix的sum=0

用到辅助矩阵sum matrix(纪录左上角矩阵和)
凡是用到需要额外计算的辅助变量的题目都比较难想,这个题tricky程度挺高
    public int[][] submatrixSum(int[][] matrix) {
        // Write your code here
        int[][] res = new int[2][2];
        if(matrix == null || matrix.length == 0|| matrix[0].length == 0)
            return res;
        int n = matrix.length;
        int m = matrix[0].length;
        //A challenge about this question is to notice sum matrix should be [n+1] *[m+1]
        //beforehand
        int[][] sum = new int[n+1][m+1];
        for(int i=1; i<=n; i++){
            for(int j=1; j<=m; j++){
                 sum[i][j] = matrix[i-1][j-1] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1];
            }
        }
        //This way actually is fcking tricky without knowing beforehand.
        for(int i=0; i<=n; i++){
            for(int h=i+1; h<=n; h++){
                HashMap
   
   
    
     map = new HashMap
    
    
     
     ();
                
                for(int j=0; j<=m; j++){
                    int diff = sum[h][j] - sum[i][j];
                    if(map.containsKey(diff)){
                        res[0][0] = i; res[0][1] = map.get(diff);
                        res[1][0] = h-1; res[1][1] = j-1;
                        return res;
                    }else{
                        map.put(diff,j);
                    }
                }
            }
        }
        return res;
    }
    
    
   
   
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值