lintcode-medium-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)]

Challenge

O(n3) time.

 

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
        if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0)
            return matrix;
        
        int m = matrix.length;
        int n = matrix[0].length;
        
        int[][] res = new int[2][2];
        
        int[][] dp = new int[m + 1][n + 1];
        dp[0][0] = 0;
        
        for(int i = 1; i < n; i++)
            dp[0][i] = 0;
        
        for(int i = 0; i < m; i++)
            dp[i][0] = 0;
        
        for(int i = 1; i <= m; i++){
            for(int j = 1; j <= n; j++){
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + matrix[i - 1][j - 1];
            }
        }
        
        for(int i = 0; i < n; i++){
            for(int j = i + 1; j <= n; j++){
                
                HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
                
                for(int k = 0; k <= m; k++){
                    int diff = dp[k][j] - dp[k][i];
                    
                    if(!map.containsKey(diff)){
                        map.put(diff, k);
                    }
                    else{
                        res[0][0] = map.get(diff);
                        res[0][1] = i;
                        res[1][0] = k - 1;
                        res[1][1] = j - 1;
                        
                        return res;
                    }
                }
                
            }
        }
        
        
        return res;
    }
}

 

posted @ 2016-04-06 18:34  哥布林工程师  阅读(109)  评论(0编辑  收藏  举报